# A dictionary is a collection of key:value pairs
# Keys are immutable objects like string, tuple and frozenset.
# Dictionary is ordered - i.e items of a dictinary always print in same order
# Dictionary is changeable - i.e we can add, remove and change items after its creation
# No duplicate key allowed.
# Dictinary item values can be of any type - i.e they support mixed data type
Python Dictionary Methods
Problem 1
- How would you add a new key to this dict?
- d = {
- "name": "Johanth",
- "language": "Python",
- "state": "Telangana",
- }
- Key name is: age
Solution 1
- 1) Using assignment operator
- 2) Using update() method
Now in code
A dictinary is a collection of key:value pairs¶
key are immuatable objects like string,frozenset¶
Dictionary is ordered - i.e items of a dictinary always print in same order¶
Dictinary is changable - i.e we can add , remove and change items after its creation¶
No duplicate items allowed - i.e no duplicate key allowed¶
dictinary item values can be of any type - i.e support mixed data type¶
In [1]:
# Creating a dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
In [2]:
# Accessing dictinary items using their keys
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
print(thisdict["year"])
Ford 1964
In [1]:
# Changing values of dictinary items using associated keys
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict) # display items before change
thisdict["brand"] = "Mercedes" # changing brand value
print(thisdict) # display items after change
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964} {'brand': 'Mercedes', 'model': 'Mustang', 'year': 1964}
In [4]:
# In Python 3.6 and earlier, dictionaries are unordered
# From Python 3.7 dictinaries ared ordered
# Ordered mean dictinary items have a defined order and it never change
# i.e items of a dictinary always print in same order
# For Ex -
dict ={"k1":5,"k2":6}
print(dict)
print(dict)
print(dict)
{'k1': 5, 'k2': 6} {'k1': 5, 'k2': 6} {'k1': 5, 'k2': 6}
In [5]:
# Length of dictnary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
3
In [6]:
# dictinary item values can be of any type - i.e support mixed data type
thisdict = {
"brand": "Ford", # string data type
"electric": False, # boolean data type
"year": 1964, # numeric data type
"colors": ["red", "white", "blue"] # list data type
}
print(thisdict)
{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
In [7]:
# type of dictinary is dict
thisdict = {
"brand": "Ford", # string data type
"electric": False, # boolean data type
"year": 1964, # numeric data type
"colors": ["red", "white", "blue"] # list data type
}
print(type(thisdict))
<class 'dict'>
In [8]:
# Accessing dictinary items using get method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)
Mustang
In [13]:
# Geting all keys as a list
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
keylist = thisdict.keys()
print(keylist)
dict_keys(['brand', 'model', 'year'])
In [14]:
# Geting all values as a list
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
valuelist = thisdict.values()
print(valuelist)
dict_values(['Ford', 'Mustang', 1964])
In [16]:
# Geting items as a list of tuple of key-value pairs
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
itemlist = thisdict.items()
print(itemlist)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
In [17]:
# The list of the keys is a view of the dictionary,
# I.e Any changes in the dictionary will reflect in key list
# For Ex - Adding a key in dictinary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
keylist = thisdict.keys()
print(keylist) # print key list before adding new item in dictinary
# Adding a new item in dictinary
thisdict["color"] = "Blue"
print(keylist) # print key list after adding new item in dictinary
print(thisdict) # print dictinary after adding new item in dictinary
dict_keys(['brand', 'model', 'year']) dict_keys(['brand', 'model', 'year', 'color']) {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Blue'}
In [18]:
# The list of the values is a view of the dictionary,
# I.e Any changes in the dictionary will reflect in value list
# For Ex - Adding a key in dictinary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
valuelist = thisdict.values()
print(valuelist) # print value list before adding new item in dictinary
# Adding a new item in dictinary
thisdict["color"] = "Blue"
print(valuelist) # print value list after adding new item in dictinary
print(thisdict) # print dictinary after adding new item in dictinary
dict_values(['Ford', 'Mustang', 1964]) dict_values(['Ford', 'Mustang', 1964, 'Blue']) {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Blue'}
In [19]:
# The list of item is a view of the dictionary,
# I.e Any changes in the dictionary will reflect in item list
# For Ex - Adding a key in dictinary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
itemList = thisdict.items()
print(itemList) # print item list before adding new item in dictinary
# Adding a new item in dictinary
thisdict["color"] = "Blue"
print(itemList) # print item list after adding new item in dictinary
print(thisdict) # print dictinary after adding new item in dictinary
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]) dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964), ('color', 'Blue')]) {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Blue'}
In [20]:
# Check if a key present in dictinary or not
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print("year" in thisdict)
print("color" in thisdict)
True False
In [ ]:
# Updating dictinary
# Add a new item using a key value
# Modifying an item value using update method
# Remove an existing item using remove method
In [22]:
# For Ex - add a new item using a key value
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "Red"
print(thisdict) # After adding new item
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Red'}
In [25]:
# For Ex - Modifying an item value using update method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year":1965})
print(thisdict) # After modifying an item
{'brand': 'Ford', 'model': 'Mustang', 'year': 1965}
In [26]:
# For Ex - Modifying an item value using associated key
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = "1976"
print(thisdict) # After modifying an item
{'brand': 'Ford', 'model': 'Mustang', 'year': '1976'}
In [28]:
# For Ex - Deleting an item value using associated key
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["year"]
print(thisdict) # After removing an item
{'brand': 'Ford', 'model': 'Mustang'}
In [33]:
# For Ex - Deleting an item value using pop method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("year") # Note passing key value
print(thisdict) # After removing an item
{'brand': 'Ford', 'model': 'Mustang'}
In [34]:
# For Ex - Deleting last item using popitem method
# Note prior to version 3.7 any item deleted randomly
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem() # To dlete last item ( No Key Passed )
print(thisdict) # After removing last item
{'brand': 'Ford', 'model': 'Mustang'}
In [29]:
# Empty a dictinary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
{}
In [31]:
# Deleting a dictinary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict # To delete a dictinary
print(thisdict) # Try to print dictinary items after deleting it , will raise an Error
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[31], line 11 3 thisdict = { 4 "brand": "Ford", 5 "model": "Mustang", 6 "year": 1964 7 } 9 del thisdict # To delete a dictinary ---> 11 print(thisdict) NameError: name 'thisdict' is not defined
In [35]:
# Itrating dictinary items
# displaying keys using for loop
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for i in thisdict:
print(i)
brand model year
In [38]:
# displaying key and associated values using for loop
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for i in thisdict:
print(str(i)+ " : " + str(thisdict[i]) )
brand : Ford model : Mustang year : 1964
In [42]:
# Iterating items through keys and values built in method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print("Keys are : ")
for k in thisdict.keys():
print(k)
print("\nValues are : ")
for v in thisdict.values():
print(v)
Keys are : brand model year Values are : Ford Mustang 1964
In [43]:
# Iterating both key and value together using items built in method
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for k,v in thisdict.items():
print(str(k) + " : " + str(v))
brand : Ford model : Mustang year : 1964
In [44]:
# Create a reference of a dictionary
# dict2 = dict1 -> Note this statment will create a new referene dict2 to dict1
# And changes made in dict1 will automatically also be made in dict2.
# For Ex -
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict2 = dict1 # Creating a reference of dict1
dict1["year"] = 1965 # Modifying an item of dict1
print(dict1) # display dict1 items
print(dict2) # display dict2 items
{'brand': 'Ford', 'model': 'Mustang', 'year': 1965} {'brand': 'Ford', 'model': 'Mustang', 'year': 1965}
In [45]:
# Create a copy of a dictionary using copy method
# Changes in any dictionary ( original or copy ) will not affect another one itmes
# For Ex -
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict2 = dict1.copy() # Creating a copy of dict1
dict1["year"] = 1965 # Modifying an item of dict1
print(dict1) # display dict1 items after changes
print(dict2) # display dict2 items after changes in dict1
{'brand': 'Ford', 'model': 'Mustang', 'year': 1965} {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
In [46]:
# Nested Dictionaries
# I.e a dictionary key value can be a dictionary as well
# For Ex - Creating a dictionary that contain three dictionary type items
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
In [47]:
# Another way of creating a nested dictionary...
# First create child dictionaries
# Then create a parent dictionary using child dictionaires
# Creating Three Child dictionaires
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
# Creating a parent dictionary
myfamily = {"child1" : child1 , "child2" : child2 , "child3" : child3}
print(myfamily)
print(type(myfamily))
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}} <class 'dict'>
In [ ]:
# Built in method associated with Dictionary data type to perform various type operations
"""
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 value
get() Returns the value of the specified key
items() Returns a list containing 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
"""
No comments:
Post a Comment