简体   繁体   中英

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;-).

You can use the dict.fromkeys() method:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM