Dictionaries in Python

Dictionary creation

A dictionary comprises of an assortment of key-value pairs. Each key-value pair maps the key to its related value. If you already know the values required, at that point the simplest method to create a dictionary is to utilize the curly braces with a comma-separated list of key: value pairs. If you need to make an empty dictionary, you can do as such with the assistance of curly braces also. Note that values in a dictionary can be of various types.

dogs = {"golden retriever": 10, "pug": 5, "chow-chow": 1}
prices = {'espresso': 5.0, 'americano': 8.0, 'latte': 10, 'pastry': 'various prices'}
empty_dict = {}


Alternative way of dictionary creation is using dict constructor:

empty_dict = dict() 


While creating a non-empty dictionary, a dict constructor can accept a dictionary as an argument, and/or future dictionary keys as argument with allocated values, as in the model:

constr = dict({'espresso': 5.0}, americano=8.0, latte=10, pastry='various prices')


At the point when we give the dict constructor dictionary keys with assigned values, as dict(americano=8.0), the left part of the expression is dealt with like a variable, so it can’t be a number, a string in quotes, a list, a multiword expression, and so on. That is, the accompanying lines will give you an error:

d1 = dict(888=8.0)
d2 = dict("americano"=8.0)
d3 = dict(["americano", "filter"]=8.0)
d4 = dict(the best americano=8.0)


Finally, you can create a nested dictionary. It’s a collection of dictionaries inside one single dictionary.

pets = {'dog': {'name': 'Dolly', 'breed': 'chow-chow'},
           'cat': {'name': 'Fluffy', 'breed': 'maine coon'}}

digits = {1: {'Word': 'one', 'Roman': 'I'}, 
          2: {'Word': 'two', 'Roman': 'II'}, 
          3: {'Word': 'three', 'Roman': 'III'}, 
          4: {'Word': 'four', 'Roman': 'IV'}, 
          5: {'Word': 'five', 'Roman': 'V'}}

Accessing the items

The syntax for getting an item is very basic — square brackets [] with a key between them. This methodology works both for adding items to a dictionary and for reading them from that point:

my_pet = {}

my_pet['name'] = 'Dolly'
my_pet['animal'] = 'dog'
my_pet['breed'] = 'chow-chow'



When working with a nested dictionary, getting the correct value might be somewhat harder. As in our example, there are various levels and you have to stop at the correct depth.

my_pets = {'dog': {'name': 'Dolly', 'breed': 'chow-chow'},
           'cat': {'name': 'Fluffy', 'breed': 'maine coon'}}


Choosing the keys

You can save object of any sort in a dictionary, yet not every one of them qualify as a key. You need a decent, exceptional(unique) key for each item in your collection. All things considered, this isn’t the main limitation on dictionary keys and we will cover them later. Just securely use numbers and strings.

At the point when a key has been added to your dictionary, its old value will be overridden:

captain_america = {'I': 'The First Avenger', 'II': 'The Winter Soldier', 'III': 'Civil War'}
captain_america['III'] = 'Avengers- Infinity War'


In Python 3.7 and up, dictionaries do maintain the insertion order for values they store, but in previous versions it is not necessarily so:

alphabet = {}
alphabet['first'] = 1
alphabet['second'] = 2


Basic operations with Dictionary

Nearly all the operations with a dictionary require a key, but not all of them need a value.

  •  Get a value from the dictionary by a key. As you remember, we can access the value in a dictionary by a key:
operation = {}
operation['key'] = 'value'


However, if you try to access a non-existent key, you will get a KeyError:

To avoid the KeyError, we can use the get method that returns None if the specified key is not in the dictionary:



With the get method we can also define the default value to be returned instead of None:

print(testable.get('not_a_key', 'default'))


  • Delete (remove from a dictionary) a value by its key with the del keyword:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
del thisdict["model"]


  • The popitem() method removes the last inserted item
my_pets = {'dog': {'name': 'Dolly', 'breed': 'chow-chow'},
           'cat': {'name': 'Fluffy', 'breed': 'maine coon'}}


  • The pop() method removes the specified key name item
my_pets = {'dog': {'name': 'Dolly', 'breed': 'chow-chow'},
           'cat': {'name': 'Fluffy', 'breed': 'maine coon'}}


  • To make a copy of a dictionary use the copy() method:
my_pets = {'dog': {'name': 'Dolly', 'breed': 'chow-chow'},
           'cat': {'name': 'Fluffy', 'breed': 'maine coon'}}
pets = my_pets.copy()


Membership testing in a Dictionary

Now and then you have to check if a particular item is available in your dictionary or not. For instance, you have a furniture catalog where items (keys) are recorded alongside costs (values), and you need to rapidly see whether there is a blue couch in it or not. In such a case, you can utilize operators in and not in for this reason. The syntax is very basic: key in dictionary returns True if key exists in dictionary and False in any case. The not in operator does the contrary thing, it returns True if key doesn’t exist in dictionary.

catalog = {'green table': 5000, 'brown chair': 1500, 'blue sofa': 15000, 'wardrobe': 10000}
print('blue sofa' in catalog)  
print('yellow chair' in catalog)
print(1500 in catalog)


Iterating over Dictionary

Other significant methods for the dictionary are those which return dictionary view object (it is a set-like article which can be specified, and has some other helpful properties): keys, items and values. As you would expect, the first gives the keys collection of a dictionary, the subsequent one gives you the collection of (key, value) pairs (tuples), and the third one gives he collection (not a set, as values probably won’t be unique in a dictionary) of values, with no data about keys that are utilized to get these values from the dictionary.

  • keys method is very helpful when you want to do something with each key in a dictionary.
tiny_dict = {'a': 1, 'b': 2, 'c': 3}



  • Iterating over keys is default behavior in Python, and sometimes you can omit the method’s call:

    tiny_dict = {'a': 1, 'b': 2, 'c': 3}
    for key in tiny_dict:


  • values method is quite similar to the previous one, with the only difference that you get the values, not the keys. Also, it’s necessary to call the method explicitly:
tiny_dict = {'a': 1, 'b': 2, 'c': 3}
for value in tiny_dict.values():


  • items method should be used in case you need both keys and values in your code:
tiny_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in tiny_dict.items():
    print(value == tiny_dict[key])


Dictionary Method

Python have some built-in dictionary methods. They are:

  • 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

Let’s try to solve a problem:

In a standard deck of cards, there are 13 of each suit. There are numbered cards (from 2 to 10) and face cards (Jack, Queen, King, and Ace). If we were to rank the face cards Jack would be 11, Queen 12, King 13 and the Ace — 14.

Write a program that calculates the average rank of one hand of cards. Don’t forget to consider the rank of the face cards.

The input format:

Six values of cards, each on a separate line.

The output format:

The average rank of the hand.

Sample Input 1:

Sample Output 1:


deck_dict = {"Ace": 14, "King": 13, "Queen": 12, "Jack": 11}
sum_cards = 0
for _ in range(6):
    item = input()
    if item in deck_dict:
        sum_cards += deck_dict[item]
        sum_cards += int(item)
print(sum_cards / 6)