All Courses
Python Dictionary

Python Dictionary

May 17th, 2019 python

What is a Dictionary in Python?

A dictionary is an unordered set or collection of items or objects where unique keys are mapped with values. These keys are used to access the corresponding paired value. While the keys are unique, values can be common and repeated. The data type of a value is also mutable and can be changed whereas, the data type of keys must be immutable such as strings, numbers or tuples. In Python, dictionaries are defined by adding curly brackets followed by adding the key: value pair which is separated by a colon as shown below.
Python Dictionary

How is it different from a list?

A dictionary is a composite data type in Python which resembles a list. However, a list has an ordered set of objects which can iterate and can be referenced and accessed by an index number unlike a dictionary which is unordered and has a key:value pair where values are accessed by keys.

Accessing an item in a dictionary

In order to  access a value in a dictionary, you can write the variable name of the dictionary followed by squared brackets inside which you can type in the key name to access its value. If you want to access a particular value with keys that contain many values, you can use indexing as shown below:

dictionary_list = {'name': 'Ariel', 'hobbies': ['painting' , 'singing' , 'cooking'] }
print ("dictionary_list['name']:", dictionary_list['name'])
print ("dictionary_list['hobbies']:", dictionary_list['name'])
//use index to access specific value
print ("dictionary_list['hobbies'][0]:", dictionary_list['name'][0])
print ("dictionary_list['hobbies'][1]:", dictionary_list['name'][1])
print ("dictionary_list['hobbies'][2]:", dictionary_list['name'][2])
Output:
dictionary_list['name']: Ariel
dictionary_list['hobbies']: ['painting, 'singing', 'cooking']
dictionary_list['hobbies'][0]: painting
dictionary_list['hobbies'][1]: singing
dictionary_list['hobbies'][2]: cooking
In the above example, the existing key ‘name’ is used to accessed its value ‘Ariel’. However, if a key  does not exist is called, it would provide an error.

Updating a dictionary

You can also update your dictionary in order to add a new entry or key:pair value, modify existing data or even delete data.

Changing existing value

dictionary_list = {'name': 'Ariel', 'hobbies': ['painting' , 'singing' , 'cooking'] }
# to change existing key's value
dictionary_list['name'] = 'Henry'
print ("dictionary_list['name']:", dictionary_list['name'])
Output:
dictionary_list[‘name’]: Henry

Adding new key:value pair

dictionary_list = {'name': 'Ariel', 'hobbies': ['painting' , 'singing' , 'cooking'] }
# to add new key:value pair
dictionary_list['age'] = 11
print ("dictionary_list:", dictionary_list)
Output:
dictionary_list: {'age': 11, 'name': 'Ariel',
'hobbies': ['painting' , 'singing' , 'cooking']}

Deleting key:value pair

dictionary_list = {'name': 'Ariel', 'hobbies': ['painting' , 'singing' , 'cooking'] }
# to delete existing key:value pair
del dictionary_list['name']
print ("dictionary_list:", dictionary_list)
Output”
dictionary_list: {'hobbies': ['painting' , 'singing' , 'cooking']}

Iterating key:value pairs using for loop

dictionary_list = {'name': 'Ariel', 'hobbies': ['painting' , 'singing' , 'cooking'] }
for x in dictionary_list["hobbies"]:
print ("hobbies ", x)
Output:
value --> painting
value --> singing
value --> cooking
Methods used in dictionaries
The following methods are already in-built and can be used on dictionaries.
Python Dictionary Method

Using clear() method

Upon using the clear() method, all the key:value pairs are removed from the dictionary so the output returns and empty dictionary.

dictionary_list = {'name': 'Ariel', 'hobbies': ['painting' , 'singing' , 'cooking'] }
dictionary_list.clear();
print (dictionary_list)
Output:
{}

Using copy() method

In order to copy a key:value pair, an existing dictionary should not be assigned to a new dictionary (for instance, dictionary_1 = dictionary_2) as changes made in dictionary_1 will affect dictionary_2 as well.  As a result, the copy() can be used to make copies of a dictionary to avoid such problem.

dictionary_1 = {'name': 'Ariel', 'hobbies': ['painting' , 'singing' , 'cooking'] }
dictionary_2 = dictionary_1.copy()
print (dictionary_2)
Output:
{'name': 'Ariel', 'hobbies': ['painting' , 'singing' , 'cooking']}

Using fromkeys() method

With the fromkeys() method, you can create a new dictionary from a sequence of elements which will be used as keys. These keys will be provided with a value.

sequence_keys = {'A', 'B', 'AB', 'O' }
value = 'blood type'
bloodtype = dict.fromkeys(sequence_keys, value)
print (bloodtype)
Output:
{'A': 'blood type', 'B': 'blood type', 'AB': 'blood type', 'O': 'blood type}

Using get() method

The get() method is used to access the value with an existing key.fruit_dictionary  = {‘fruit’:’mango’, ‘color’:’yellow’, ‘seed’:’yes’ }

fruit_color = fruit_dictionary.get('color')
print (fruit_color)
Output:
yellow
Using items() method

items() method can be used to list all the keys in a dictionary along with their values.

fruit_dictionary  = {'fruit':'mango', 'color':'yellow', 'seed':'yes' }for k, v in fruit_dictionary.items():
print (k, v)
Output:
fruit mangocolor yellow
seed yes

Using keys() method

All the keys in a dictionary can be listed by using the keys() method.

student_dictionary  = {'name' : 'Lisa', 'age' : 6, 'grade' : '1' }student_keys = student_dictionary.keys()
print (student_keys)
Output:
dict_keys(['name', 'age', 'grade'])

Using pop() method

The pop() method is used to remove a selected item from the dictionary.

student_dictionary  = {'name' : 'Lisa', 'age' : 6, 'grade' : '1' }
student_dictionary.pop('grade')
print (student_dictionary)
Output:
{'name': 'Lisa', 'age': 6 }

Using popitem() method

The last item in a dictionary will be removed with the popitem() method.

student_dictionary  = {'name' : 'Lisa', 'age' : 6, 'grade' : '1' }
student_dictionary.pop('grade')
print (student_dictionary)
Output:
{'name': 'Lisa', 'age': 6 }

Using setdefault() method

This method is used to return the value of the selected key. If the key exists in the dictionary, the value is returned as it is in the dictionary. If the key does not exist, it can be added with a chosen value.

dog = { "breed": "labrador", "color": "dusty white", "sex": "female" }
x = dog.setdefault("color", "black")
print(x)
Output:

dusty white

Using update() method

The values within a dictionary can be updated or changed by  assigning a new value to the specified key.

dict = {1: "one", 2: "three"}
dict_update = {2: "two"}
#value of key 2 is updated
dict.update(dict_update)
print(dict)
Output:
{1: 'one', 2: 'two'}

Using values() method

A list of all the values within the dictionary will be listed. 

dog = { "breed": "labrador", "color": "dusty white", "sex": "female" }
x = dog.values()
print(x)
Output:
dict_values(['labrador', 'dusty white', 'female'])

Python Dictionary | Python Tutorial For Beginners

Social Share:

0 responses on "Python Dictionary"

Leave a Message

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