Python list comprehensions dictionary

Create a dictionary with comprehension

Can I use list comprehension syntax to create a dictionary? For example, by iterating over pairs of keys and values:

Related: collections.Counter is a specialized type of dict for counting things: Using a dictionary to count the items in a list

17 Answers 17

Use a dict comprehension (Python 2.7 and later):

Alternatively, use the dict constructor (for str keys only):

pairs = [('a', 1), ('b', 2)] dict(pairs) # → dict((k, v + 10) for k, v in pairs) # →

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

keys = ['a', 'b'] values = [1, 2] dict(zip(keys, values)) # →

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?

@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.Counter

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

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

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) >>> gen = ((i, i+1) for i in range(1, 6, 2)) >>> gen at 0xb7201c5c> >>> dict(gen)

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:

You’re looking for the phrase «dict comprehension» — it’s actually:

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:

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

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

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:

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

In Python 2.7, it goes like:

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

Python version >= 2.7, do the below:

Python version < 2.7 (RIP, 3 July 2010 — 31 December 2019) , do the below:

d = dict((i,True) for i in [1,2,3]) 

To add onto @fortran’s answer, if you want to iterate over a list of keys key_list as well as a list of values value_list :

d = dict((key, value) for (key, value) in zip(key_list, value_list)) 

Just to throw in another example. Imagine you have the following list:

and you want to turn it into a dict where the key is the index and value is the element in the list. You can do so with the following line of code:

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.

Here is another example of dictionary creation using dict comprehension:

What i am tring to do here is to create a alphabet dictionary where each pair; is the english letter and its corresponding position in english alphabet

>>> import string >>> dict1 = >>> dict1 >>> 

Notice the use of enumerate here to get a list of alphabets and their indexes in the list and swapping the alphabets and indices to generate the key value pair for dictionary

Hope it gives a good idea of dictionary comp to you and encourages you to use it more often to make your code compact

This code will create dictionary using list comprehension for multiple lists with different values that can be used for pd.DataFrame()

#Multiple lists model=['A', 'B', 'C', 'D'] launched=[1983,1984,1984,1984] discontinued=[1986, 1985, 1984, 1986] #Dictionary with list comprehension keys=['model','launched','discontinued'] vals=[model, launched,discontinued] data = #Convert dict to dataframe df=pd.DataFrame(data) display(df) 

enumerate will pass n to vals to match each key with its list

def get_dic_from_two_lists(keys, values): return

Assume we have two lists country and capital

country = ['India', 'Pakistan', 'China'] capital = ['New Delhi', 'Islamabad', 'Beijing'] 

Then create dictionary from the two lists:

print get_dic_from_two_lists(country, capital) 

Adding to @Ekhtiar answer, if you want to make look up dict from list , you can use this:

names = ['a', 'b', 'd', 'f', 'c'] names_to_id = #

Or in rare case that you want to filter duplicate, use set first (best in list of number):

names = ['a', 'b', 'd', 'f', 'd', 'c'] sorted_list = list(set(names)) sorted_list.sort() names_to_id = # names = [1,2,5,5,6,2,1] names_to_id = #

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 as an improvement.

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.

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

Python supports dict comprehensions, which allow you to express the creation of dictionaries at runtime using a similarly concise syntax.

A dictionary comprehension takes the form . This syntax was introduced in Python 3 and backported as far as Python 2.7, so you should be able to use it regardless of which version of Python you have installed.

A canonical example is taking two lists and creating a dictionary where the item at each position in the first list becomes a key and the item at the corresponding position in the second list becomes the value.

The zip function used inside this comprehension returns an iterator of tuples, where each element in the tuple is taken from the same position in each of the input iterables. In the example above, the returned iterator contains the tuples (“a”, 1), (“b”, 2), etc.

Источник

Using List Comprehension with Dictionaries in Python

I’m trying to get my head around list comprehensions and I can understand the basics of how they work but I get the feeling I should be able to do something with my code here that I just can’t seem to get working. Given a dictionary:

There are a couple of snippets that I feel I should be able to reduce to fewer lines if I knew better:

for k, v in d.items(): dag[k] = v for val in v: if val not in d.keys(): dag[val] = None 
t = [] for k, v in d.items(): if not v: t.append(k) d.pop(k) 
for [k, v in d.items() if not v]: 

But that keeps telling me it needs an else statement and none of what I have read has helped answer how/if this is possible.

Clarity is better than briefness, so only make it shorter if it remains as clear or clearer to read. That also tends to be fast, in Python.

2 Answers 2

If you want to keep the keys that have falsey values the syntax is:

[ k for k, v in d.items() if not v] 

That is equivalent to your last loop bar the d.pop(k) which I am not sure if you want. The first k is what we append to the list, for k, v is each key and value in d.items and if not v means we only keep the k’s that have falsey values.

If you actually want a dict without those keys and value you can use a dict comprehension where the logic is exactly the same except we are creating key/value pairings instead of just keeping just the keys in the list comprehension:

As for your first code, I am not sure what you want it to do exactly but you should not be calling .keys , in python2 that creates a list and makes lookups O(n) as opposed to 0(1) and in python 3 it is an unnecessary function call.

In your first snippet, you are essentially defaulting all nodes to None in the dag . You could invert those steps and avoid testing for keys already being present altogether:

dag = dict.fromkeys(node for v in d.values() for node in v) dag.update(d) 

This creates a dictionary with all None values for the given keys (sourced from a generator expression), then updated to insert all known edges.

In your code you used if val not in d.keys() ; this is functionally equivalent to if val not in d , but without the redundant call to d.keys() , which creates a new object (in Python 2, a list with all keys, making the search extra inefficient, in Python 3 a dictionary view is created). Always use the shorter form there.

Do be aware that the set objects you use as values in d are now shared with dag ; any changes you make to these sets will be reflected across both dictionaries.

Creating a sequence of nodes without values would then be:

nodes_without_exits = [node for node, edges in d.items() if not node] 

List comprehensions still need the producer expression, the part that produces the value to be inserted into the list; here that’s node , the list is built out of the keys of the dictionary.

Источник

Читайте также:  Что такое predicate java
Оцените статью