Dictionaries !
Along with lists, dictionaries are one of the most flexible built-in data types in Python.
If you think of lists as ordered collections of objects, you can think of dictionaries as
unordered collections; the big distinction is that in dictionaries, items are stored and
fetched by key, instead of by position. Dictionaries take the place of records, search tables, and any other sort of aggregation where item names are more meaningful than item positions.
>>> avengers = {'Scarlet Witch': 'Wanda Maximoff', 'Thor': 'Eric Masterson',
'Ant-Man': 'Hank Pym'}
as you can see a dictionary is written as a series of key:value
pairs, separated by commas, enclosed in curly braces.
Here’s a rundown of their main properties. Python dictionaries are:
- Accessed by key, not offset position
- Unordered collections
- Variable-length, heterogeneous, and arbitrarily nestable
Q: Those are some big words, Can you break that down a bit?
A: Here’s a breakdown.
Accessed by key, not offset positions
Dictionaries associate a set of values with keys, so you can fetch an item out of a dictionary using the key under which you originally storedit. You use the same indexing operation to get components in a dictionary as you do in a list, but the index takes the form of a key, not a relative offset.
The Noobs of Python : Ep.2 - List and List of List ! and the List goes on!
Unordered collections of arbitrary objects
Unlike in a list, items stored in a dictionary aren’t kept in any particular order; in
fact, Python pseudo-randomizes their left-to-right order to provide quick lookup.
Keys provide the symbolic (not physical) locations of items in a dictionary.
Variable-length, heterogeneous, and arbitrarily nestable
Like lists, dictionaries can grow and shrink in place, they can contain objects of any type,
and they support nesting to any depth (they can contain lists, other dictionaries, and so on).
Each key can have just one associated value, but that value can be a collection of multiple objects if needed, and a given value can be stored under any number of keys.
Q: Fair enough, can we see some in action ?
A: Here is a list of known Avengers and their alias.
avengers = {'Thor': 'Eric Masterson', 'Captain America': 'Steve Rodgers',
'Hawkeye': 'Clint Barton', 'Power Man': 'Luke Cage',
'Scarlet Witch': 'Wanda Maximoff', 'Quicksilver': 'Pietro Maximoff',
'The Black Knight': 'Dane Whitmann', 'Black Panther': 'TChalla',
'She-Hulk': 'Jennifer Walters', 'Wonder Man': 'Simon Williams',
'Wasp': 'Janet Van Dyne', 'The Sentry': 'Robert Reynolds',
'Iron Man': 'Tony Stark', 'Black Widow': 'Natasha Romanov',
'Goliath': 'Dr.Bill Foster', 'Ant-Man': 'Hank Pym'}
This assigns a dictionary to the avengers variable. This dictionary’s keys are
'Thor' , 'Captain America' , 'Hawkeye' and so on. The values for these keys are 'Eric Masterson' , 'Steve Rodgers' ,and 'Clint Barton' , respectively. You can access these values through their keys:
>>> avengers['Thor']
'Eric Masterson'
>>> avengers['Black Panther']
'TChalla'
>>> avengers['Goliath']
'Dr.Bill Foster'
>>>
>>> 'My favorite Thor host ' + avengers['Thor'] + ' was the best !!!'
'My favorite Thor host Eric Masterson was the best !!!'
>>>
Dictionaries can still use integer values as keys, just like lists use integers for indexes,
but they do not have to start at 0 and can be any number. ex:
>>> mighty_avengers = {1 : 'Captain Marvel', 2 : 'Ant Man', 3 : 'Falcon'}
>>> mighty_avengers
{1: 'Captain Marvel', 2: 'Ant Man', 3: 'Falcon'}
>>>
The built-in len
function works on dictionaries too; it returns the number of items
stored in the dictionary or the length of its keys list. The dictionary in
operator allows you to test for key existence, and the keys
method returns
all the keys in the dictionary. The latter of these can be useful for processing dictionaries
sequentially, but you shouldn’t depend on the order of the keys list.
>>> len(avengers)
16
>>> len(mighty_avengers)
3
>>> 'Wasp' in avengers
True
>>> list(avengers.keys())
['Hawkeye', 'Captain America', 'Wonder Man', 'Scarlet Witch', 'Quicksilver',
'The Black Knight', 'Black Widow', 'Ant-Man', 'She-Hulk', 'Black Panther',
'The Sentry', 'Iron Man', 'Power Man', 'Thor', 'Goliath', 'Wasp']
>>>
>>>
>>> list(avengers.items())
[('Hawkeye', 'Clint Barton'), ('Captain America', 'Steve Rodgers'),
('Wonder Man', 'Simon Williams'), ('Scarlet Witch', 'Wanda Maximoff'),
('Quicksilver', 'Pietro Maximoff'), ('The Black Knight', 'Dane Whitmann'),
('Black Widow', 'Natasha Romanov'), ('Ant-Man', 'Hank Pym'),
('She-Hulk', 'Jennifer Walters'), ('Black Panther', 'TChalla'),
('The Sentry', 'Robert Reynolds'), ('Iron Man', 'Tony Stark'),
('Power Man', 'Luke Cage'), ('Thor', 'Eric Masterson'),
('Goliath', 'Dr.Bill Foster'), ('Wasp', 'Janet Van Dyne')]
Notice
The value returned by the value()
and items()
method are tuples of the key and value pair.
More to come in the next Ep.2.x Tuples
Here, the in
and not in
operators can check whether a value exists in a list. You can also use these operators to see whether
a certain key or value exists in a dictionary.
>>> 'Captain America' in avengers
True
>>> 'Captain America' in avengers.values()
False
>>> 'Captain America' in avengers.keys()
True
>>> 'Captain America' not in avengers
False
>>> 'Captain America' not in avengers.values()
True
>>>
Q: What else can I do with dictionaries? Can I add/ manipulate them?
A: YUP ! Dictionaries, like lists, are mutable, so you can change, expand, and shrink them in place
without making new dictionaries, simply assign a value to a key to change or create an entry.
The del
statement works here, too! Here are some examples :
>>> mighty_avengers
{1: 'Captain Marvel', 2: 'Ant Man', 3: 'Falcon'}
>>> mighty_avengers[3] = ['Falcon', 'Sam Wilson', 'All-New Captain America']
>>> mighty_avengers
{1: 'Captain Marvel', 2: 'Ant Man',
3: ['Falcon', 'Sam Wilson', 'All-New Captain America']}
>>> del mighty_avengers[1]
>>> mighty_avengers
{2: 'Ant Man',
3: ['Falcon', 'Sam Wilson', 'All-New Captain America']}
>>> mighty_avengers[1] = 'Iron Man'
>>> mighty_avengers
{1: 'Iron Man', 2: 'Ant Man',
3: ['Falcon', 'Sam Wilson', 'All-New Captain America']}
>>>
Q: This should keep me busy for some time, Thanks !
A: There is more to come. There's a lot to do with Dictionaries.
An entry to Methods to the Madness for dictionaries is on the way !
Code on Code_Warriors !