Three ways of creating dictionaries in Python
Dictionaries are the fundamental data structure in Python, and a key tool in any Python programmer’s arsenal. They allow O(1) lookup speed, and have been heavily optimized for memory overhead and lookup speed efficiency.
Today I”m going to show you three ways of constructing a Python dictionary, as well as some additional tips and tricks.
Dictionary literals
Perhaps the most commonly used way of constructing a python dictionary is with curly bracket syntax:
d = {"age":25}
As dictionaries are mutable, you need not know all the entries in advance:
# Empty dict d = {} # Fill in the entries one by one d["age"] = 25
From a list of tuples
You can also construct a dictionary from a list (or any iterable) of key, value pairs. For instance:
d = dict([("age", 25)])
This is perhaps most useful in the context of a list comprehension:
class Person(object): def __init__(self, name, profession): self.name = name self.profession = profession people = [Person("Nick", "Programmer"), Person("Alice","Engineer")] professions = dict([ (p.name, p.profession) for p in people ]) >>> print professions {"Nick": "Programmer", "Alice": "Engineer"}
This is equivalent, though a bit shorter, to the following:
people = [Person("Nick", "Programmer"), Person("Alice","Engineer")] professions = {} for p in people: professions[p.name] = p.profession
This form of creating a dictionary is good for when you have a dynamic rather than static list of elements.
From two parallel lists
This method of constructing a dictionary is intimately related to the prior example. Say you have two lists of elements, perhaps pulled from a database table:
# Static lists for purpose of illustration names = ["Nick", "Alice", "Kitty"] professions = ["Programmer", "Engineer", "Art Therapist"]
If you wished to create a dictionary from name to profession, you could do the following:
professions_dict = {} for i in range(len(names)): professions_dict[names[i]] = professions[i]
This is not ideal, however, as it involves an explicit iterator, and is starting to look like Java. The more Pythonic way to handle this case would be to use the zip
method, which combines two iterables:
print zip(range(5), ["a","b","c","d","e"]) [(0, "a"), (1, "b"), (2, "c"), (3, "d"), (4, "e")] names_and_professions = zip(names, professions) print names_and_professions [("Nick", "Programmer"), ("Alice", "Engineer"), ("Kitty", "Art Therapist")] for name, profession in names_and_professions: professions_dict[name] = profession
As you can see, this is extremely similar to the previous section. You can dispense the iteration, and instead use the dict
method:
professions_dict = dict(names_and_professions) # You can dispence the extra variable and create an anonymous # zipped list: professions_dict = dict(zip(names, professions))
“Three ways of creating dictionaries in Python Developmentality” was a remarkable article and also I
actually was in fact truly content to locate it. Thanks for the post,Natasha
Hey Nick, cool article, I’m learning Python now in one of my classes. But under the “From a List of Tuples” in the last script, I think you meant to say “for p in people” instead of “for p in professions”.
Thanks – fixed it
Very helpful, thanks!
thaanks,
i just want to make it like that:
a function(key0=value0,key1=value1,…….)
and return a dictionary with keys and values
def mkdict(**kwargs):
return kwargs
or use the dict function: https://docs.python.org/2/library/stdtypes.html#dict
hello.. what if I have a loooong list of existing string keys and I don’t want to enter them all individually by hand? and to each key is associated a column of a 2D -array? how can I use a loop to populate such a dictionary? I have no clue so far…
Thanks
I don’t understand. Yes you can create a dictionary using a loop. Something like:
>>> d = {}
>>> for k, v in [(“k1”, “v1”), (“k2”, “v2”)]:
… d[k] = v
…
>>> print d
{‘k2’: ‘v2’, ‘k1’: ‘v1’}
You can write it a little more compact:
professions = dict([ (p.name, p.profession) for p in people ])
is the same as
professions = {p.name: p.profession for p in people}
an I find it better to read than the dict([…]) syntax
Nice tip!
Thank you verry much, I was trying to create a dict with the zip(), and I found it here, thank you, it’s verry helpful.