简体   繁体   中英

How to replace keys (key labels) in a dictionary from a list of tokens

I have a dictionary

dict = {'a': 'cat', 'b':'dog'}

and I want to replace the keys in the dict with new keys (or key labels) from a list ['c', 'd'] so that I get (the same)

dict = {'c': 'cat', 'd':'dog'} . How can I do this?

You can define the relation between the old keys and their replacements, in another dictionary, like this. Here, mapping is the dictionary which maps the old keys with the new keys.

d, mapping = {'a': 'cat', 'b':'dog'}, {"a":"c", "b":"d"}
print {mapping[k]:v for k, v in d.items()}

Output

{'c': 'cat', 'd': 'dog'}

As already has been pointed out, a dictionary is not ordered. So if you want to replace your keys with values from a list (which is ordered), you will need to specify how the keys of your dict are ordered. Something along these lines:

def replaceKeys (d, newKeys, sort):
    return {newKeys[idx]: v for idx, (_, v)
        in enumerate(sorted(d.items(), key = lambda kv: sort(kv[0])))}

d = {'cat': 'gato', 'dog': 'chucho', 'mule': 'mula'}
d2 = replaceKeys(d, ['a', 'b', 'c'], lambda oldKey: oldKey) #sort alphabetically
print(d2)
d2 = replaceKeys(d, ['a', 'b', 'c'], lambda oldKey: -len(oldKey)) #sort by length ascending
print(d2)
d2 = replaceKeys(d, ['a', 'b', 'c'], lambda oldKey: oldKey[2]) #sort by third letter
print(d2)

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