Dictionaries¶
The following content and the code excerpts have been derived from the following sources:
- Dictionaries, LearnPython.org. https://www.learnpython.org/en/Dictionaries
- Merging two Dictionaries. https://www.geeksforgeeks.org/python-merging-two-dictionaries/
- How to Loop a Dictionary. https://www.mkyong.com/python/python-how-to-loop-a-dictionary/
- Dictionary methods in Python. https://www.geeksforgeeks.org/dictionary-methods-in-python-set-1-cmp-len-items/
"A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it."¶
A dictionary can be identified using curly braces.Creating Dictionaries¶
In [7]:
phonebook = {} #empty dictionary is defined
#adding elements using keys and values
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
print(type(phonebook))
In [6]:
#dictionary can be defined as follows too
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print(phonebook)
print(type(phonebook))
Accessing, Modifying and Deleting items in a Dictionary¶
Accessing items in a Dictionary¶
Dictionaries use the keys in the key-value pairs to access its elements. We can use the functions items() to access the items in a ditionary.
Syntax: dictionary.items()
Syntax: dictionary.items()
In [9]:
print(phonebook['John']) #prints the value associated with the key 'John' in the dictionary phonebook
In [20]:
#We can iterate over the items in a dictionary using loops
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
print (phonebook.items()) #gives the list of key-value pairs
Modifying items in a Dictionary¶
We can use the update() function to modify an item in the dictionary or simply use the = operator.
In [25]:
phonebook.update({'Jill': 938118406}) #assigns new value to the item with the key 'Jill' using update() function
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
In [24]:
phonebook['Jill'] = 845126794 #assigns new value to the item with the key 'Jill' using = operator
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
Deleting Items in a Dictionary¶
We can use the del() function or the pop() function to delete items from a Dictionary
In [26]:
del phonebook["John"]
print(phonebook)
In [27]:
phonebook.pop("John") #throws error because the key 'John' does not exist in the dictionary object phonebook anymore
print(phonebook)
In [28]:
phonebook.pop("Jill")
print(phonebook)
Merging two dictionaries¶
There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Python. In this article, we will discuss few ways of merging dictionaries.
Using the method update()¶
By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None.
In [58]:
def Merge(dict1, dict2):
return(dict2.update(dict1))
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
dict3 = {'e': 2, 'f': 0}
Merge(dict1, dict2)
# changes made in dict2
print(dict2)
Using ** in Python (WORKS in python 3.5 or higher)¶
This is generally considered a trick in Python where a single expression is used to merge two dictionaries and stored in a third dictionary. The single expression is . This does not affect the other two dictionaries. implies that the argument is a dictionary. Using [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. For more information refer kwargs in Python. Using this we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.
In [31]:
def Merge(dict1, dict2):
res = {** dict1, ** dict2}
return res
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
dict3 = Merge(dict1, dict2)
print(dict3)
In [35]:
stocks = {
'IBM': 146.48,
'MSFT':44.11,
'CSCO':25.54
}
#looping over the keys (when only one variable is used, here c, it can be understood as refering to the keys)
for c in stocks:
print(c)
In [36]:
for k, v in stocks.items(): #when 2 varaibles are used the first one identifies keys and the second identifies values
print(k,v)
In [43]:
for k, v in stocks.items():
print("Code : {0}, Value : {1}".format(k, v)) #Another Way to use the keys and values when printing
for k, v in stocks.items():
print("Value : {0}, Code : {1}".format(v, k))
for k, v in stocks.items():
print("Code : {1}, Value : {0}".format(v, k))
Looping Over Key and values without using Items¶
In [47]:
d = {"first_name": "Alfred", "last_name":"Hitchcock"}
for k in d:
print("{} = {}".format(k, d[k]))