Python - Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
Create and print a dictionary:
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
print(dict)
{'brand': 'apple', 'model': '10s', 'year': 2019}
We can access the items of a dictionary by referring to its key name, inside square brackets.There is also a method called get() that will give you the same result.
1.USING 'keyname':
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
x=dict["brand"]
print(x)
apple
2.USING get():
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
x=dict.get("model")
print(x)
10s
We can change the value of a specific item by referring to its key name.
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
dict["year"]=2018
{'brand': 'apple', 'model': '10s', 'year': 2018}
We 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.
Print all key names in the dictionary, one by one :
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
for i in dict:
print (i)
brand
model
year
Print all values in the dictionary, one by one :
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
for i in dict:
print (dict[i])
apple
10s
2019
You can also use the values() function to return values of a dictionary :
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
for i in dict.values():
print (i)
apple
10s
2019
Loop through both keys and values, by using the items() function :
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
for i,i2 in dict.items():
print (i,i2)
brand apple
model 10s
year 2019
To determine if a specified key is present in a dictionary use the 'in' keyword.
Check if "model" is present in the dictionary :
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
if "model" in dict:
print("yes,'model' is one of the keys in dict")
yes,'model' is one of the keys in dict
To determine how many items (key-value pairs) a dictionary has,we have to use the len() method.
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
print(len(dict))
3
Adding an item to the dictionary is done by using a new index key and assigning a value to it.
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
dict["color"]="red"
print(dict)
{'brand': 'apple', 'model': '10s', 'year': 2019, 'color': 'red'}
There are several methods to remove items from a dictionary.They are:
pop( ), popitem( ), del , clear( ).
The pop() method removes the item with the specified key name ;
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
dict.pop("model")
print(dict)
{'brand': 'apple', 'year': 2019}
The popitem( ) method removes the last inserted item (in versions before 3.7, a random item is removed instead):
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
dict.popitem()
print(dict)
{'brand': 'apple','model': '10s'}
The del keyword removes the item with the specified key , and can also delete the dictionary completely.
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
del dict["model"]
print(dict)
{'brand': 'apple', 'year': 2019}
NOW,using del without keyword
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
del dict
print(dict)
##it gets an error as dict gets deleted
The clear() keyword empties the dictionary:
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
dict.clear()
print (dict)
{}
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().
dict={
"brand":"apple",
"model":"10s",
"year" : 2019
}
dict1=dict.copy()
print(dict1)
{'brand': 'apple', 'model': '10s', 'year': 2019}
Another way to make a copy is to use the built-in method dict().
dict1={
"brand":"apple",
"model":"10s",
"year" : 2019
}
dict2=dict(dict1)
print(dict2)
{'brand': 'apple', 'model': '10s', 'year': 2019}
A dictionary can also contain many dictionaries, this is called nested dictionaries.
myfamily = {
"parent1":{
"name":"jayy",
"age":45
},
"parent2" :{
"name":"sweejya",
"age":35
},
"child1":{
"name":"sanvi",
"age":21
},
"child2":{
"name":"suhansh",
"age":19
},
"child3":{
"name":"pranjal",
"age":18
}
}
print(myfamily)
==== O/P ======
{'parent1': {'name': 'jayy', 'age': 45}, 'parent2': {'name': 'sweejya', 'age': 35}, 'child1': {'name': 'sanvi', 'age': 21}, 'child2': {'name': 'suhansh', 'age': 19}, 'child3': {'name': 'pranjal', 'age': 18}}
If you want to nest three dictionaries that already exists as dictionaries
child1={
"name":"sanvi",
"age":21
}
child2={
"name":"suhansh",
"age":19
}
child3={
"name":"pranjal",
"age":18
}
myfamily={
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
======= O/P =========
{'child1': {'name': 'sanvi', 'age': 21}, 'child2': {'name': 'suhansh', 'age': 19}, 'child3': {'name': 'pranjal', 'age': 18}}
It is also possible to use the dict() constructor to make a new dictionary.
dict1=dict(brand="apple",model="10s",year=1964)
print(dict1)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
=====O/P====
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Method | Description |
---|---|
clear() | Removes all the elements from the dictionary |
copy() | Returns a copy of the dictionary |
fromkeys() | Returns a dictionary with the specified keys and values |
get() | Returns the value of the specified key |
items() | Returns a list containing the a tuple for each key value pair |
keys() | Returns a list containing the dictionary's keys |
pop() | Removes the element with the specified key |
popitem() | Removes the last inserted key-value pair |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
update() | Updates the dictionary with the specified key-value pairs |
values() | Returns a list of all the values in the dictionary |