Home > Python > Three ways of creating dictionaries in Python

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))

Further reading



Categories: Python Tags: , , ,
  1. February 5, 2013 at 1:09 am

    “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

  2. Nathan Dunn
    March 6, 2013 at 2:08 pm

    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”.

    • i82much
      March 6, 2013 at 3:37 pm

      Thanks – fixed it

  3. February 6, 2016 at 7:03 pm

    Very helpful, thanks!

  4. badr eddine
    April 3, 2016 at 4:20 pm

    i just want to make it like that:
    a function(key0=value0,key1=value1,…….)
    and return a dictionary with keys and values

  1. February 4, 2013 at 9:02 am
  2. January 30, 2014 at 9:00 am
  3. March 1, 2015 at 3:15 pm
  4. November 25, 2015 at 5:54 am
  5. October 9, 2016 at 1:42 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: