Saturday , December 21 2024
Python Dictionary - Properties of Dictionary Keys & Values Built-in Dictionary Func

Python Dictionary

Python Dictionary

Python Dictionary

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and does not allow duplicates. Dictionaries are written with curly brackets, and have keys and values: {‘Key’:’Value’}

Note:As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

In [1]:
D = {}
print(D)
{}
In [2]:
D = {'Name':'Kevin','Age':30,'Marks':89.78}
print(D)
{'Name': 'Kevin', 'Age': 30, 'Marks': 89.78}
In [3]:
print(D['Name'])
print(D['Age'])
print(D['Marks'])
Kevin
30
89.78

Duplicates Not Allowed

  • Dictionaries cannot have two items with the same key and Duplicate values will overwrite existing values:
In [4]:
D = {'Name':'Kevin','Age':30,'Marks':89.78,'Age':56}
print(D)
{'Name': 'Kevin', 'Age': 56, 'Marks': 89.78}

Dictionary Length and Type

In [5]:
print(D)
{'Name': 'Kevin', 'Age': 56, 'Marks': 89.78}
In [6]:
print(len(D))
3
In [7]:
print(type(D))
<class 'dict'>

Dictionary Items

  • The values in dictionary items can be of any data type:
In [8]:
D = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021,
  "colors": ["black", "white", "red"]
}
In [9]:
print(D)
{'brand': 'Tesla', 'electric': True, 'year': 2021, 'colors': ['black', 'white', 'red']}

Accessing Items

In [10]:
print(D)
{'brand': 'Tesla', 'electric': True, 'year': 2021, 'colors': ['black', 'white', 'red']}
In [11]:
print(D['brand'])
Tesla

There is also a method called get() that will give you the same result:

In [12]:
print(D.get('brand'))
Tesla

Get all Keys

In [13]:
print(D.keys())
dict_keys(['brand', 'electric', 'year', 'colors'])

Get all Values

In [15]:
print(D.values())
dict_values(['Tesla', True, 2021, ['black', 'white', 'red']])

The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.

In [17]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021,
}
x = car.keys()

print(x) #before the change

car["color"] = "black"

print(x) #after the change
dict_keys(['brand', 'electric', 'year'])
dict_keys(['brand', 'electric', 'year', 'color'])

Make a change in the original dictionary, and see that the values list gets updated as well:

In [18]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021,
}
x = car.values()

print(x) #before the change

car["color"] = "black"

print(x) #after the change
dict_values(['Tesla', True, 2021])
dict_values(['Tesla', True, 2021, 'black'])

Get Items

  • The items() method will return each item in a dictionary, as tuples in a list.
In [19]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021,
}
print(car.items())
dict_items([('brand', 'Tesla'), ('electric', True), ('year', 2021)])

Make a change in the original dictionary, and see that the items list gets updated as well:

In [20]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021,
}
x = car.items()

print(x) #before the change

car["color"] = "black"

print(x) #after the change
dict_items([('brand', 'Tesla'), ('electric', True), ('year', 2021)])
dict_items([('brand', 'Tesla'), ('electric', True), ('year', 2021), ('color', 'black')])

Check if Key Exists

  • To determine if a specified key is present in a dictionary use the in keyword:
In [21]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021,
}

if "brand" in car:
    print("Yes, 'brand' is one of the keys in the car dictionary")
Yes, 'brand' is one of the keys in the car dictionary

Change Dictionary Items

In [23]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021,
  "color": 'black'
}
print(car)
{'brand': 'Tesla', 'electric': True, 'year': 2021, 'color': 'black'}
In [24]:
car['color'] = 'white'
print(car)
{'brand': 'Tesla', 'electric': True, 'year': 2021, 'color': 'white'}

Update the “year” of the car by using the update() method:

In [26]:
car.update({"year": 2022})
print(car)
{'brand': 'Tesla', 'electric': True, 'year': 2022, 'color': 'white'}

Add Dictionary Items

In [27]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021,
}
print(car)
{'brand': 'Tesla', 'electric': True, 'year': 2021}
In [28]:
car['color'] = 'black'
print(car)
{'brand': 'Tesla', 'electric': True, 'year': 2021, 'color': 'black'}

Update Dictionary

  • The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.
  • The argument must be a dictionary, or an iterable object with key:value pairs.
In [31]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021
}
print(car)
{'brand': 'Tesla', 'electric': True, 'year': 2021}
In [32]:
car.update({"color": "black"})
print(car)
{'brand': 'Tesla', 'electric': True, 'year': 2021, 'color': 'black'}

Remove Dictionary Items

  • The pop() method removes the item with the specified key name:
In [33]:
print(car)
{'brand': 'Tesla', 'electric': True, 'year': 2021, 'color': 'black'}
In [34]:
car.pop('electric')
print(car)
{'brand': 'Tesla', 'year': 2021, 'color': 'black'}

The del keyword removes the item with the specified key name:

In [35]:
print(car)
{'brand': 'Tesla', 'year': 2021, 'color': 'black'}
In [36]:
del car['year']
print(car)
{'brand': 'Tesla', 'color': 'black'}

The del keyword can also delete the dictionary completely:

In [37]:
del car
print(car)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-37-3e96a2fb7a5b> in <module>
      1 del car
----> 2 print(car)

NameError: name 'car' is not defined

The clear() method empties the dictionary:

In [38]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021
}
car.clear()
print(car)
{}

Loop Through a Dictionary

  • You can loop through a dictionary by using a for loop.
  • When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
In [39]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021
}
In [40]:
for i in car:
    print(i)
brand
electric
year
In [41]:
for i in car:
    print(car[i])
Tesla
True
2021

You can also use the values() method to return values of a dictionary:

In [43]:
for i in car.values():
    print(i)
Tesla
True
2021

You can use the keys() method to return the keys of a dictionary:

In [44]:
for i in car.keys():
    print(i)
brand
electric
year

Loop through both keys and values, by using the items() method:

In [45]:
for i in car.items():
    print(i)
('brand', 'Tesla')
('electric', True)
('year', 2021)
In [47]:
for i,j in car.items():
    print(i,j)
brand Tesla
electric True
year 2021

Copy a Dictionary

  • You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
  • There are ways to make a copy, one way is to use the built-in Dictionary method copy().
In [48]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021
}

car2 = car
print(car)
print(car2)
{'brand': 'Tesla', 'electric': True, 'year': 2021}
{'brand': 'Tesla', 'electric': True, 'year': 2021}
In [49]:
car['year']=2022
print(car)
print(car2)
{'brand': 'Tesla', 'electric': True, 'year': 2022}
{'brand': 'Tesla', 'electric': True, 'year': 2022}
In [50]:
car = {
  "brand": "Tesla",
  "electric": True,
  "year": 2021
}

car2 = car.copy()
print(car)
print(car2)
{'brand': 'Tesla', 'electric': True, 'year': 2021}
{'brand': 'Tesla', 'electric': True, 'year': 2021}
In [51]:
car['year']=2022
print(car)
print(car2)
{'brand': 'Tesla', 'electric': True, 'year': 2022}
{'brand': 'Tesla', 'electric': True, 'year': 2021}

Nested Dictionary

In [52]:
myfamily = {
  "child1" : {
    "name" : "Kevin",
    "year" : 2009
  },
  "child2" : {
    "name" : "Ronaldo",
    "year" : 2011
  },
  "child3" : {
    "name" : "Keisha",
    "year" : 2013
  }
}
In [53]:
print(myfamily)
{'child1': {'name': 'Kevin', 'year': 2009}, 'child2': {'name': 'Ronaldo', 'year': 2011}, 'child3': {'name': 'Keisha', 'year': 2013}}
In [55]:
print(myfamily['child1'])
print(myfamily['child1']['name'])
print(myfamily['child1']['year'])
{'name': 'Kevin', 'year': 2009}
Kevin
2009

Dictionary of a list

In [58]:
d={'Name':['Kevin','Ranaldo','Keisha'],'Age':[31,33,34]}
print(d)
print(d['Name'])
print(d['Age'])
print(d.keys())
print(d.values())
print(d.items())
{'Name': ['Kevin', 'Ranaldo', 'Keisha'], 'Age': [31, 33, 34]}
['Kevin', 'Ranaldo', 'Keisha']
[31, 33, 34]
dict_keys(['Name', 'Age'])
dict_values([['Kevin', 'Ranaldo', 'Keisha'], [31, 33, 34]])
dict_items([('Name', ['Kevin', 'Ranaldo', 'Keisha']), ('Age', [31, 33, 34])])
In [59]:
for i,j in d.items():
    print(i,j)
Name ['Kevin', 'Ranaldo', 'Keisha']
Age [31, 33, 34]
In [64]:
for i,j in d.items():
    print("Key:",i)
    for val in j:
        print(val)
    print()
Key: Name
Kevin
Ranaldo
Keisha

Key: Age
31
33
34

About Machine Learning

Check Also

Python MySQL Insert Into Table

Python MySQL Insert Into Table

4 Python MySQL Insert Into Table Python MySQL Insert Into Table¶To fill a table in …

Leave a Reply

Your email address will not be published. Required fields are marked *