[英]Make unlimited versions of a dict, same keys, different values
如果我有字典,该如何获取密钥,并允许用户使用每个密钥的不同值制作无限的版本?
my_keys = ["Hello", "World"]
my_values1 = ["Why", "that"]
my_dict1 = dict(zip(my_keys, my_values1))
my_dict2 = dict.fromkeys(my_dict1.keys())
Variant 1 allows simple construction of any dict from both: a list of keys and values, while my_dict2 presents a varaint to create an "empty" (all values are None
dict from an existing. You can also mix both (I leave that as an exercise;-). 变体1允许从以下两者简单地构造任何dict:键和值的列表,而my_dict2则提供了一个变体来创建“空”(所有值都是现有的
None
dict。您也可以将两者混合使用(我将其保留为行使;-)。
You can use the dict.fromkeys()
method: 您可以使用
dict.fromkeys()
方法:
def copy_keys(your_dict=None):
if your_dict != None:
return dict.fromkeys(your_dict.keys())
else:
return dict()
blah = dict((('blah',1),('haha',2)))
>>>blah
{'blah': 1, 'haha': 2}
>>> copy_keys(blah)
{'blah': None, 'haha': None}
My example function initalizes the values as None
but you can easily adapt it to insert your own values by passing the value
parameter to the .fromkeys(seq[,value])
method. 我的示例函数将值
.fromkeys(seq[,value])
为None
但是您可以通过将value
参数传递给.fromkeys(seq[,value])
方法来轻松地将其插入自己的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.