简体   繁体   English

制作字典的无限版本,相同的键,不同的值

[英]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.

相关问题 根据字典中的相同键对值求和并生成数组 - Sum values based on same keys in dict and make array 如何比较来自两个不同字典的相同键值 - How to compare same keys values from two different dict 在python中使用dict键作为不同字典中的值 - Using dict keys in python as values in a different dict 将字典转换为具有相同键、值和布局的列表 - Convert dict to list with same keys, values and layout 对于两个不同字典的公用值,使字典键相同 - Make dictionary keys to be the same for common values of two different dictionaries 如何在执行集合操作 set(A.values()) - set(B.values()) 后获取 dict A 的键,因为它们的所有键都不同但很少有值相同 - How to get keys of dict A after performing set operation set(A.values()) - set(B.values()) cause their all keys are different but few values are same 具有相同键名的字典 - Dict with same keys names 什么是减少和合并 list(list(dict())) 的有效方法,其中一些字典可能具有相同的键但不同的值 - What is an efficient way to reduce and merge a list(list(dict())) where some of the dictionaries might have the same keys but different values 在dict中乘以键*值? - Multiply keys*values in a dict? XML 使用具有多个键值的相同标签来 dict Python - XML to dict Python with same tags that have multiple keys values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM