Python Dictionary

Python Dictionary is an unordered pool of data values. It is used for storing data values such as a map, which holds a single value as an element. The Python dictionary holds key-value pairs. The key value is included in the dictionary to make it better optimized.

Python Dictionary

Dictionary is a collection of key-value pairs.

Syntax:

”’ a = {“key”: “value”,

“Sandeep”: “code”,

“marks” : “100”,

“list”: [1,2,9]}

a[“key”] # Prints value

a[“list”] # Prints [1,2,9] ”’

Properties of Python Dictionaries

  1. It is unordered
  2. It is mutable
  3. It is indexed
  4. It cannot contain duplicate keys

Dictionary Methods

Consider the following dictionary,

a = {“name”: “Sandeep”,

“from”: “India”,

“marks”: [92,98,96]}

  1. items() : returns a list of (key,value) tuple.
  2. keys() : returns a list containing dictionary’s keys.
  3. update({“friend”: “Sam”}) : updates the dictionary with supplied key-value pairs.
  4. get(“name”) : returns the value of the specified keys (and value is returned e.g., “Sandeep” is returned here)

Creating a Dictionary

Let’s try to build a profile of three people using dictionaries. To do that you separate the key-value pairs by a colon(“:”). The keys would need to be of an immutable type, i.e., data-types for which the keys cannot be changed at runtime such as int, string, tuple, etc. The values can be of any type. Individual pairs will be separated by a comma(“,”) and the whole thing will be enclosed in curly braces({...}).

For example, you can have the fields “city”, “name,” and “food” for keys in a dictionary and assign the key,value pairs to the dictionary variable person1_information.

>>> person_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}
>>> type(person1_information)
<class 'dict'>
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam', 'food': 'shrimps'}

Get the values in a Dictionary

To get the values of a dictionary from the keys, you can directly reference the keys. To do this, you enclose the key in brackets [...] after writing the variable name of the dictionary.

So, in the following example, a dictionary is initialized with keys “city”, “name,” and “food” and you can retrieve the value corresponding to the key “city.”

>>> create a dictionary person1_information
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food":         "shrimps"}
>>> print the dictionary
>>> print(person1_information["city"])
San Francisco

You can also use the get method to retrieve the values in a dict. The only difference is that in the get method, you can set a default value. In direct referencing, if the key is not present, the interpreter throws KeyError.

>>> # create a small dictionary
>>> alphabets = {1: ‘a’}
>>> # get the value with key 1
>>> print(alphabets.get(1))
'a'
>>> # get the value with key 2. Pass “default” as default. Since key 2 does not exist, you get “default” as the return value.
>>> print(alphabets.get(2, "default"))
'default'
>>> # get the value with key 2 through direct referencing 
>>> print(alphabets[2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 2

Looping over dictionary

Say, you got a dictionary, and you want to print the keys and values in it. Note that the key-words for and in are used which are used when you try to loop over something. To learn more about looping please look into tutorial on looping.

>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}
>>> for k, v in person1_information.items():
...     print("key is: %s" % k)
...     print("value is: %s" % v)
...     print("###########################")
...
key is: food
value is: shrimps
###########################
key is: city
value is: San Francisco
###########################
key is: name
value is: Sam
###########################

Add elements to a dictionary

You can add elements by updating the dictionary with a new key and then assigning the value to a new key.

>>> # initialize an empty dictionary
>>> person1_information = {}

>>> # add the key, value information with key “city”
>>> person1_information["city"] = "San Francisco"
>>> # print the present person1_information
>>> print(person1_information)
{'city': 'San Francisco'}

>>> # add another key, value information with key “name”
>>> person1_information["name"] = "Sam"
>>> # print the present dictionary
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam'}

>>> # add another key, value information with key “food”
>>> person1_information["food"] = "shrimps"
>>> # print the present dictionary
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam', 'food': 'shrimps'}

Or you can combine two dictionaries to get a larger dictionary using the update method.

>>> # create a small dictionary
>>> person1_information = {'city': 'San Francisco'}

>>> # print it and check the present elements in the dictionary
>>> print(person1_information) 
{'city': 'San Francisco'}

>>> # have a different dictionary
>>> remaining_information = {'name': 'Sam', "food": "shrimps"}

>>> # add the second dictionary remaining_information to personal1_information using the update method
>>> person1_information.update(remaining_information)

>>> # print the current dictionary
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam', 'food': 'shrimps'}

Delete elements of a dictionary

To delete a key, value pair in a dictionary, you can use the del method.

>>> # initialise a dictionary with the keys “city”, “name”, “food”
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}

>>> # delete the key, value pair with the key “food”
>>> del person1_information["food"]

>>> # print the present personal1_information. Note that the key, value pair “food”: “shrimps” is not there anymore.
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam'}

A disadvantage is that it gives KeyError if you try to delete a nonexistent key.

>>> # initialise a dictionary with the keys “city”, “name”, “food”
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}

>>> # deleting a non existent key gives key error.
>>> del person1_information["non_existent_key"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'non_existent_key'

So, instead of the del statement you can use the pop method. This method takes in the key as the parameter. As a second argument, you can pass the default value if the key is not present.

>>> # initialise a dictionary with key, value pairs
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}

>>> # remove a key, value pair with key “food” and default value None
>>> print(person1_information.pop("food", None))
'Shrimps'

>>> # print the updated dictionary. Note that the key “food” is not present anymore
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam'}

>>> # try to delete a nonexistent key. This will return None as None is given as the default value.
>>> print(person1_information.pop("food", None))
None

More methods are available on docs.python.org

Was this article helpful?
YesNo

Leave a Comment

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