7 minutes read

You already know how to create a dictionary and access its items. In this topic, you are going to learn about other features of dictionaries.

Alternative dictionary creation

You know that there are two ways to create a dictionary. Using curly braces with a comma-separated list of key: value pairs or the dict constructor. We will learn about the fromkeys method that creates a new dictionary with specified keys and values. This is the syntax for this method:

dict.fromkeys(keys, value)

The keys parameter is a sequence of elements that will become the keys of a new dictionary. The value parameter is optional and defaults to None, but the user can specify a value for all keys in the dictionary. Look at the example below:

planets = {'Venus', 'Earth', 'Jupiter'}  
  
# initializing by default with None 
planets_dict = dict.fromkeys(planets)
print(planets_dict)  # {'Jupiter': None, 'Venus': None, 'Earth': None}

# initializing with a value
value = 'planet'
planets_dict = dict.fromkeys(planets, value)
print(planets_dict)  # {'Earth': 'planet', 'Venus': 'planet', 'Jupiter': 'planet'}

# changing the value of 'Jupiter'
planets_dict['Jupiter'] = "giant " + planets_dict['Jupiter']
print(planets_dict)
 # {'Earth': 'planet', 'Venus': 'planet', 'Jupiter': 'giant planet'}

The word was added successfully! But now we want to create a dictionary that would store the names of the satellites for those planets. Some planets have several satellites, and some do not have them at all, so it is more convenient to use a list as a value.

# some satellites of the Solar System
satellites = ['Moon', 'Io', 'Europa']

# initializing with an empty list
planets_dict = dict.fromkeys(planets, [])
print(planets_dict)  # {'Jupiter': [], 'Venus': [], 'Earth': []}

Let's add the items from the satellites list to the corresponding planets. Look, this is what happened to our dictionary:

planets_dict['Earth'].append(satellites[0])
planets_dict['Jupiter'].append(satellites[1])
planets_dict['Jupiter'].append(satellites[2])
print(planets_dict)  
# {'Jupiter': ['Moon', 'Io', 'Europa'], 'Venus': ['Moon', 'Io', 'Europa'], 'Earth': ['Moon', 'Io', 'Europa']}

We see that all the elements of the satellites list have been assigned to all planets in our dictionary. This happened because the fromkeys method assigns the same object to all keys. While referring to different keys of the planets_dict dictionary, we are still referring to the same list. The difference from the previous example is that if we use mutable objects (a list, a dictionary) as values, all changes will also apply to our dictionary. The solution is to use the dictionary comprehension:

planets_dict = {key: [] for key in planets}

More details on this operation will be provided in another topic on dictionary operations.

Adding items

Suppose we want to add items to an existing dictionary. You know one way to do it — define a new key and a new value: existing_dict['new key'] = 'new value'. But there is another way — use the update method. The method updates the dictionary with new elements from another dictionary or an iterable of key-value pairs.

Let's create a dictionary and define months as keys, and the average temperature for this month as values. So we have the following testable dictionary:

testable = {'September': '16°C', 'December': '-10°C'} 
another_dictionary = {'June': '21°C'}

# adding items from another dictionary
testable.update(another_dictionary)
print(testable)  # {'September': '16°C', 'December': '-10°C', 'June': '21°C'}

# adding a key-value pair
testable.update(October='10°C')
print(testable)  
# {'September': '16°C', 'December': '-10°C', 'June': '21°C', 'October': '10°C'}

If the specified key already exists in the dictionary, the method will update the key with the new value:

testable = {'September': '16°C', 'December': '-10°C'}
testable.update(December='-20°C')

print(testable)  # {'September': '16°C', 'December': '-20°C'}

With Python 3.10, you can use the union operator (|) to merge two dictionaries. If a key appears in both operands, the value from the right-hand operand prevails, overwriting any previous value associated with that key.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

merged_dict = dict1 | dict2

print(merged_dict) # {'a': 1, 'b': 3, 'c': 4}

Summary

What have we learned in this topic?

  • a new fromkeys method for alternative dictionary creation; we also found out its peculiarities,

  • discovered how to add new items to the dictionary with the update method,

If you want to see more information on dictionaries, don't forget to check out the Python documentation.

822 learners liked this piece of theory. 12 didn't like it. What about you?
Report a typo