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?
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.
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.
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.
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With