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

  5. Sylvie
    July 18, 2018 at 2:50 pm

    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…

    • i82much
      July 18, 2018 at 3:03 pm

      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’}

  6. piko
    May 7, 2020 at 1:28 am

    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

    • i82much
      May 7, 2020 at 8:39 am

      Nice tip!

  7. August 15, 2020 at 6:37 pm

    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.

  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
  6. April 7, 2017 at 8:26 am
  7. October 19, 2021 at 7:47 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 )

Connecting to %s

%d bloggers like this: