Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dictionary from an iterable

Tags:

What is the easiest way to create a dictionary from an iterable and assigning it some default value? I tried:

>>> x = dict(zip(range(0, 10), range(0))) 

But that doesn't work since range(0) is not an iterable as I thought it would not be (but I tried anyways!)

So how do I go about it? If I do:

>>> x = dict(zip(range(0, 10), 0)) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: zip argument #2 must support iteration 

This doesn't work either. Any suggestions?

like image 583
user225312 Avatar asked Nov 03 '10 06:11

user225312


People also ask

How to create a new Python dictionary using only one iterable?

We can create a new Python dictionary using only one iterable if we choose to generate either the keys or the values on the fly. When we choose to generate the values on the fly, we can use the items in the iterable as the keys and vice versa.

How to create a new dictionary based on a condition?

We can also create a new dictionary by selecting key value pairs from another dictionary based on a certain condition. For this task we can get the list of key value pairs as tuples using items()method and then we can use the tuples having key value pairs to create a new dictionary according to any given condition.

How do you create a dictionary with already defined key value pairs?

Create dictionary with key value pairs already defined To create a dictionary using already defined key value pairs, we can either use the curly braces, dictionary constructor or dictionary comprehension.

How to iterate through a dictionary in Python using for loop?

To iterate through a dictionary in Python by using .keys (), you just need to call .keys () in the header of a for loop: When you call .keys () on a_dict, you get a view of keys.


2 Answers

In python 3, You can use a dict comprehension.

>>> {i:0 for i in range(0,10)} {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0} 

Fortunately, this has been backported in python 2.7 so that's also available there.

like image 110
Jeff Mercado Avatar answered Oct 01 '22 23:10

Jeff Mercado


You need the dict.fromkeys method, which does exactly what you want.

From the docs:

fromkeys(...)     dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.     v defaults to None. 

So what you need is:

>>> x = dict.fromkeys(range(0, 10), 0) >>> x {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0} 
like image 39
user225312 Avatar answered Oct 01 '22 23:10

user225312