new_dict = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
The following defines a dictionary that maps countries with their capital:
world_map = {
'Italy': 'Rome',
'Japan': 'Tokio',
'Canada': 'Ottawa',
'Bolivia': 'La Paz',
'Egypt': 'Cairo'
}
You can also construct a dictionary with the built-in dict() function. The argument to dict() should be a sequence of key-value pairs. A list of tuples works well for this:
new_dict = dict([
(<key>,<value>),
(<key>,<value>),
.
.
.
(<key>,<value>)
])
world_map dictionary can then also be defined this way:
world_map = dict([
('Italy', 'Rome'),
('Japan', 'Tokio'),
('Canada', 'Ottawa'),
('Bolivia', 'La Paz'),
('Egypt', 'Cairo')
])
If the key values are simple strings, they can be specified as keyword arguments. So here is yet another way to define world_map dict:
world_map = dict(
Italy='Rome',
Japan='Tokio',
Canada='Ottawa',
Bolivia='La Paz',
Egypt='Cairo'
)
Once you’ve defined a dictionary, you can display its contents, the same as you can do for a list. All three of the definitions shown above appear as follows when displayed:
type(world_map)
world_map
The entries in the dictionary display in the order they were defined. But the order is not maintained when we retrieve these elements from the dictionary. Dictionary elements can not be accessed by numerical index.
world_map[1]
world_map['Canada']
world_map['Italy']
If you refer to a key that is not in the dictionary, Python raises an exception:
world_map['Spain']
Adding an entry to an existing dictionary is simply a matter of assigning a new key and value:
world_map['South Africa'] = 'Pretoria'
world_map
Python Update Dictionary
If you want to update an entry, you can just assign a new value to an existing key:
world_map['Bolivia'] = 'Sucre'
world_map
Python Remove Entry in Dictionary
To delete an entry, use the del statement, specifying the key to delete:
del world_map['Egypt']
world_map
world_map['France']
world_map[1]
Note that both of the above errors are same. In both cases, it is "KeyError". [1] is not index but it is a key.
Look at below example where I am using integers as keys in Python dictionaries.
fruits = {
0: 'apple',
1: 'banana',
2: 'lemon',
3: 'pear',
4: 'watermelon'
}
fruits[0]
fruits[3]
In the expressions world_map[1], fruits[0], and fruits[2], the numbers in square brackets are keys not indices. Also since these are keys, the order of items in the dictionary is not maintained. If change the order of these keys, let us say in reverse order, you would still get the same values using the same keys:
fruits = {
4: 'watermelon',
3: 'pear',
2: 'lemon',
1: 'banana',
0: 'apple'
}
fruits[0]
fruits[3]
The syntax may look similar, but you can’t treat a dictionary like a list:
type(fruits)
fruits[-1]
fruits[1:3]
fruits.append('pineapple')
Building a Python Dictionary Incrementally
In many cases, we dont know the content of Python dictionaries in advance and need to fill up the key,values as the need arises. For that we need to first define a empty dictionary and then you can add new keys and values one at a time. Let us go through an example to illusterate that.
restaurant = {}
type(restaurant)
restaurant['name'] = 'Delicious Food Restaurant'
restaurant['category'] = 'fast food'
restaurant['menu'] = ['pizza', 'french fries', 'sandwich', 'donuts']
restaurant['workers'] = 8
restaurant['address'] = {
'street': '1800 Lincoln Avenue',
'city': 'San Francisco',
'state': 'California'
}
restaurant
restaurant['name']
restaurant['menu']
restaurant['workers']
Retrieving the values in the sublist or subdictionary requires an additional index or key:
restaurant['menu'][2]
restaurant['menu'][-1]
Python Dictionary with Different Key Types
Python dictionaries are very robust, they can be of any type.
In restaurant dict, some of the values are strings, one is an integer, one is a list, and one is another dictionary.
new_dict = {
3.14: 'This is a float key',
88: 'This is an integer key',
True: 'This is a bool key'
}
new_dict[True]
new_dict[3.14]
new_dict[88]
Note in below example, our keys are of type integer, float, and Boolean.
new_dict = {
3.14: 'This is a float key',
88: 'This is an integer key',
True: 'This is a bool key'
}
new_dict
You can even use built-in Python objects like types and functions.
obj_dict = { int: 45, float: 2.7183, bool: True }
obj_dict[float]
obj_dict[bool]
obj_dict = { bin: 0, hex: 1, oct: 2}
obj_dict[bin]
obj_dict[oct]
Duplicate Keys in Python Dictionary
However, there are couple of things to watch for when we are dealing with Python dictionaries. Python dictionaries don't allow duplicate dictionaries. Every key in Python dictionary has a value. If we try to enter the same key in Python dictionary, the key value is overwritten. Let us show this with an example.
world_map = {
'Italy': 'Rome',
'Japan': 'Tokio',
'Canada': 'Ottawa',
'Bolivia': 'La Paz',
'Egypt': 'Cairo',
'Nigeria': 'Lagos'
}
world_map['Nigeria'] = 'Abuja'
world_map
Also if you define the same key again while defining a Python dictionary. Dictionary key's value is overwritten by the latter. Checkout following code to learn this concept.
world_map = {
'Italy': 'Rome',
'Japan': 'Tokio',
'Nigeria': 'Lagos',
'Canada': 'Ottawa',
'Bolivia': 'La Paz',
'Egypt': 'Cairo',
'Nigeria': 'Abuja'
}
world_map
Note in the above example, 'Nigeria' key's value is 'Abuja' not 'Lagos'.
Tuple as Python Dictionary Keys
A tuple can also be a dictionary key, because tuples are immutable:
food_inventory = {
(1, 1): 'eggs',
(1, 2): 'butter',
(2, 1): 'cheese',
(2, 2): 'bacon',
(3, 1): 'milk',
(3, 2): 'juice',
(3, 3): 'yogurt'
}
food_inventory[(1, 1)]
food_inventory[(2, 1)]
food_inventory[(3, 2)]
However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable:
food_inventory = {
[1,1]: 'eggs',
[1,2]: 'butter',
[2,1]: 'cheese',
[2,2]: 'bacon',
[3,1]: 'milk',
[3,2]: 'juice',
[3,3]: 'yogurt'
}
Note: Why does the above error message say unhashable
Python keys should be hashable that means Python should be able to generate a fixed unique value using its built-in hash() function. If the key is not hashable, then Python throws an exception.
hash('hashed string')
hash(['hashed','string'])
app = {
'Twitter': 'social media network',
'YouTube': 'social media network',
'Instagram': 'social media network'
}
app
Below code checks if the value key values are same.
app['Twitter'] == app['YouTube'] == app['Instagram']
world_map = {
'Norway': 'Oslo',
'India': 'New Delhi',
'Mexico': 'Mexico City',
'Venezuela': 'Caracas',
'Ghana': 'Accra'
}
'Norway' in world_map
'China' in world_map
'China' not in world_map
You can use the in operator together with short-circuit evaluation to avoid raising an error when trying to access a key that is not in the dictionary:
world_map['Spain']
'Spain' in world_map and world_map['Spain']
The len() function returns the number of key-value pairs in a dictionary:
world_map = {
'Norway': 'Oslo',
'India': 'New Delhi',
'Mexico': 'Mexico City',
'Venezuela': 'Caracas',
'Ghana': 'Accra'
}
len(world_map)
- dict.clear()
- dict.get()
- dict.items()
- dict.keys()
- dict.values()
- dict.pop()
- dict.popitem()
- dict.update()
dict.clear()
clear() empties dictionary of all key-value pairs:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
solar_system
solar_system.clear()
solar_system
dict.get()
get() searches dictionary for and returns the associated value if it is found. If is not found, it returns None:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
position = solar_system.get('Earth')
print(position)
position = solar_system.get('Saturn')
print(position)
If is not found and the optional argument is specified, that value is returned instead of None
position = solar_system.get('Pluto', 'This planet was not found')
print(position)
position = solar_system.get('Pluto', -1)
print(position)
dict.items()
items() returns a list of tuples containing the key-value pairs. The first item in each tuple is the key, and the second item is the key’s value:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
solar_system
list(solar_system.items())
list(solar_system.items())[1][0]
list(solar_system.items())[1][1]
dict.keys()
keys() returns a list of all keys:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
solar_system
list(solar_system.keys())
dict.values()
values() returns a list of all values:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
solar_system
list(solar_system.values())
dict.pop()
If is present in dictionary, pop() removes and returns its associated value:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
solar_system
solar_system.pop('Mars')
solar_system
pop() raises a KeyError exception if is not in dictionary:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
solar_system.pop('Neptune')
If is not in d, and the optional argument is specified, then that value is returned, and no exception is raised:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
solar_system.pop('Neptune', -1)
solar_system.pop('Neptune', 'This planet was not found')
solar_system
dict.popitem()
popitem() removes the last key-value pair added from dictionary and returns it as a tuple:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3}
solar_system.popitem()
solar_system
solar_system.popitem()
solar_system
If dictionary is empty, popitem() raises a KeyError exception
solar_system = {}
solar_system.popitem()
dict.update()
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3, 'Pluto': 9}
new_solar_system = {'Pluto': -1, 'Mercury': 1, 'Jupiter': 5}
solar_system.update(new_solar_system)
solar_system
may also be a sequence of key-value pairs, similar to when the dict() function is used to define a dictionary. For example, can be specified as a list of tuples:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3, 'Pluto': 9}
solar_system.update([('Jupiter', 5), ('Pluto', -1)])
solar_system
Or the values to merge can be specified as a list of keyword arguments:
solar_system = {'Mars': 4, 'Venus': 2, 'Earth': 3, 'Pluto': 9}
solar_system.update(Jupiter=5, Pluto=-1)
solar_system
from Planet Python
via read more
No comments:
Post a Comment