Create a dictionary with list comprehension

1,024,668

Solution 1

Use a dict comprehension (Python 2.7 and later):

{key: value for (key, value) in iterable}

Alternatively for simpler cases or earlier version of Python, use the dict constructor, e.g.:

pairs = [('a', 1), ('b', 2)]
dict(pairs)                         #=> {'a': 1, 'b': 2}
dict([(k, v+1) for k, v in pairs])  #=> {'a': 2, 'b': 3}

Given separate arrays of keys and values, use the dict constructor with zip:

keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values))  #=> {'a': 1, 'b': 2}
2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))

Solution 2

In Python 3 and Python 2.7+, dictionary comprehensions look like the below:

d = {k:v for k, v in iterable}

For Python 2.6 or earlier, see fortran's answer.

Solution 3

In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}

Solution 4

Create a dictionary with list comprehension in Python

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}

You're looking for the phrase "dict comprehension" - it's actually:

mydict = {k: v for k, v in iterable}

Assuming blah blah blah is an iterable of two-tuples - you're so close. Let's create some "blahs" like that:

blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]

Dict comprehension syntax:

Now the syntax here is the mapping part. What makes this a dict comprehension instead of a set comprehension (which is what your pseudo-code approximates) is the colon, : like below:

mydict = {k: v for k, v in blahs}

And we see that it worked, and should retain insertion order as-of Python 3.7:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah2': 'blah', 'blah3': 'blah'}

In Python 2 and up to 3.6, order was not guaranteed:

>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}

Adding a Filter:

All comprehensions feature a mapping component and a filtering component that you can provide with arbitrary expressions.

So you can add a filter part to the end:

>>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
>>> mydict
{'blah0': 'blah', 'blah2': 'blah'}

Here we are just testing for if the last character is divisible by 2 to filter out data before mapping the keys and values.

Solution 5

In Python 2.7, it goes like:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

Zip them!

Share:
1,024,668
flybywire
Author by

flybywire

Updated on July 08, 2022

Comments

  • flybywire
    flybywire almost 2 years

    I like the Python list comprehension syntax.

    Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

    mydict = {(k,v) for (k,v) in blah blah blah}  # doesn't work
    
  • Andre Simon
    Andre Simon over 7 years
    you could have used zip
  • Jean-François Corbett
    Jean-François Corbett over 7 years
    This doesn't address the question at all.
  • johnnydrama
    johnnydrama over 6 years
    Nice answer - simplified: d = {k: v+1 for v, k in enumerate(string.ascii_lowercase)}
  • cryanbhu
    cryanbhu almost 5 years
    what if I have a case of list of words ['cat','dog','cat'] and I want to make a dict with key as word and value as count? Is there a short efficient syntax for that?
  • fortran
    fortran almost 5 years
    @cryanbhu if what you mean is to count the repetitions of a given element in the list, there's a Counter class in the collections package: docs.python.org/2/library/collections.html#collections.Count‌​er
  • Mahmoud
    Mahmoud over 4 years
    same idea: reduce(lambda p, q: {**p, **dict([q])}, bla bla bla, {})
  • Subfuzion
    Subfuzion over 2 years
    The OP's question specified "For example, by iterating over pairs of keys and values", so most of the answers focus on that. However, I upvoted this because it is a good example for handling the list to dictionary use case.
  • bjrne
    bjrne over 2 years
    v:k in the first codeblock is misleading, it reads like value:key which is the wrong way around to create a dict. I'd suggest {name:index for index, name in enumerate(names)} as an improvement.
  • bjrne
    bjrne over 2 years
    Also, you don't need the second part at all. Since it's a dict, it will by design remove duplicates by overwriting the entry.
  • Muhammad Yasirroni
    Muhammad Yasirroni over 2 years
    @bjrne I preserve the original answer on that and I don't feel it misleading at all. Nope, the second part is to make lookup dict. If you not use set, the index will not in order. It's rare case and I also give the output, so just use if that is your use case.
  • Timo
    Timo about 2 years
    What I was looking for: create a dict from an ordinary List.