Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dict.fromkeys all point to same list

Tags:

python

This was causing me a bit of grief...

I created a dictionary from a list

l = ['a','b','c'] d = dict.fromkeys(l, [0,0]) # initializing dictionary with [0,0] as values  d['a'] is d['b'] # returns True 

How can I make each value of the dictionary a seperate list? Is this possible without iterating over all keys and setting them equal to a list? I'd like to modify one list without changing all the others.

like image 769
Michael Johnston Avatar asked Mar 20 '13 06:03

Michael Johnston


People also ask

Do Dict Keys return same order?

No, there is no guaranteed order for the list of keys returned by the keys() function. In most cases, the key list is returned in the same order as the insertion, however, that behavior is NOT guaranteed and should not be depended on by your program.

What is the difference between keys () and items () in dictionary?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.

How do you get a list of all the values in a dictionary?

In Python to get all values from a dictionary, we can use the values() method. The values() method is a built-in function in Python and returns a view object that represents a list of dictionaries that contains all the values.

What is the use of Fromkeys () give example?

Example 1: Python Dictionary fromkeys() with Key and Value In the above example, we have used the fromkeys() method to create the dictionary with the given set of keys and string value . Here, the fromkeys() method creates a new dictionary named vowels from keys and value .


1 Answers

You could use a dict comprehension:

>>> keys = ['a','b','c'] >>> value = [0, 0] >>> {key: list(value) for key in keys}     {'a': [0, 0], 'b': [0, 0], 'c': [0, 0]} 
like image 136
Blender Avatar answered Sep 30 '22 16:09

Blender