Home > OS >  How to change a value inside a list which is a value for a key in a dictionary?
How to change a value inside a list which is a value for a key in a dictionary?

Time:11-10

I try to change one value inside the list but all values change for all keys.

vertex_list = ['a','b']
distance_dict = dict.fromkeys(vertex_list, [10, 'None'])
distance_dict['a'][0] = 1
print(distance_dict)

output:

{'a': [1, 'None'], 'b': [1, 'None']}

when I built the dictionary with traditional { } it works fine. I guess the problem is for the list inside dict.fromkeys, which creates one list for all dictionary keys. is there a solution to fix it. without using ''for'' and { } to build the dictionary?

CodePudding user response:

Quoting from the official documentation,

fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.

Means that dict.fromkeys is useful if the second argument is a singleton instance(like None). So the solution is to use the dict comprehension.

distance_dict = {vertex: [10, None] for vertex in vertex_list} 

CodePudding user response:

You can solve with:

vertex_list = ['a','b']
distance_dict =  {x: [10, 'None'] for x in vertex_list}
distance_dict['a'][0] = 1
print(distance_dict)

Output:

{'a': [1, 'None'], 'b': [10, 'None']}

CodePudding user response:

If you print the id of distance_dict 's value created by dict.fromkeys:

vertex_list = ['a','b']
distance_dict = dict.fromkeys(vertex_list, [10, 'None'])

print(id(distance_dict['a']), id(distance_dict['b']))
print(id(distance_dict['a']) == id(distance_dict['b']))

Output:

2384426495040 2384426495040
True

distance_dict['a'] and distance_dict['b'] are actually the same list object, occupying the same memory space.

If you use the dict comprehension:

distance_dict = {vertex: [10, None] for vertex in vertex_list}
print(id(distance_dict['a']) == id(distance_dict['b']))

Output:

False

They are different list objects with the same elements.

  • Related