Python dict.fromkeys()生成list()的副本,而不是新副本 [英] Python dict.fromkeys() generates copies of list() instead of a new one

查看:89
本文介绍了Python dict.fromkeys()生成list()的副本,而不是新副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用dict.fromkeys()方法生成字典.我有一个list年,我想给values个他们分配一个list object.问题是dict.fromkeys()生成列表的副本.因此,当我更新列表元素时,它会更新所有副本.

I want to generate a dictionary using dict.fromkeys() method. I have a years list and i want to assign values them a list object. The problem is that dict.fromkeys() generates copies of list. So, when i update elements of list, it updates all of copies.

>>> years=["1","2","3"]
>>> names=["a","b","c"]
>>> blank=[]
>>> names_in_years=dict.fromkeys(years,blank.copy())
>>> names_in_years
{'2': [], '4': [], '3': [], '1': []}
>>> names_in_years["2"].extend(names)
>>> names_in_years
{'2': ['a', 'b', 'c'], '4': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '1': ['a', 'b', 'c']}

我想分别更新dictionary个对象.结果低于我想要的:

I want to update dictionary objects, individually.the result is below that i want:

{'2': ['a', 'b', 'c'], '4': [], '3': [], '1': []}

是否有一种方法可以在一行中执行此操作?

Is there a method to do this in a single line?

推荐答案

只需

names_in_years["2"] = names_in_years["2"] + names

而不是笨拙

names_in_years["2"].extend(names)

前者将新值分配给旧值,后者则将返回的值适当地改变.在处理更新键值时,分配通常比就地突变更安全,更可靠.

The former assigns the new value to the old one, the latter mutates the returned value in place. In dealing with updating key values, assignment is usually safer and more foolproof than in-place mutation.

这篇关于Python dict.fromkeys()生成list()的副本,而不是新副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆