Abhishek Bhatia
Abhishek Bhatia

Reputation: 9806

Replace keys in a dictionary

I have a dictionary

event_types={"as":0,"ah":0,"es":0,"eh":0,"os":0,"oh":0,"cs":0,"ch":0}

How can I replace a by append, s by see, h by horse, e by exp with a space in between.

Output something like:

{"append see":0,"append horse":0,"exp horse":0....}

Upvotes: 12

Views: 6609

Answers (4)

user1514631
user1514631

Reputation: 1222

First create a mapping dictionary to map the single letters to words:

mm={"a":"append", "s":"see","h":"horse","e":"exp","c":"corn","o":"ocelot"}

then transform your input dictionary to a list of key, value tuples, rewrite the key using the mapping dict and create a new list of tuples consisting of new key, original value, finally transform the list of tuples to a dict.

dict(map(lambda e: ("%s %s" % (mm[e[0][0]], mm[e[0][1]]), e[1]), event_types.items()))

Upvotes: 4

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Not sure if you can append or not, but you can do the following one liner:

>>> dict={}
>>> dict={"a":"b"}
>>> dict["aha"]=dict.pop("a")
>>> dict
{'aha': 'b'}

You can traverse the keys and change them according to your need.

Upvotes: 4

thefourtheye
thefourtheye

Reputation: 239473

Have another dictionary with your replacements, like this

keys = {"a": "append", "h": "horse", "e": "exp", "s": "see"}

Now, if your events look like this

event_types = {"as": 0, "ah": 0, "es": 0, "eh": 0}

Simply reconstruct it with dictionary comprehension, like this

>>> {" ".join([keys[char] for char in k]): v for k, v in event_types.items()}   
{'exp see': 0, 'exp horse': 0, 'append see': 0, 'append horse': 0}

Here, " ".join([keys[char] for char in k]), iterates the characters in the k, fetches corresponding words from keys dictionary and forms a list. Then, the elements of the list are joined with space character, to get the desired key.

Upvotes: 19

Amadan
Amadan

Reputation: 198324

Iterate on keys and values of the original dictionary, transform the key, then store the value in the result dictionary using the transformed key. To transform the key, map over its characters, replace by looking up in a mapping dictionary ({ "a" : "append", ... }), then join with spaces.

Upvotes: 3

Related Questions