U13-Forward
U13-Forward

Reputation: 71580

Best way to split key:value pair into two pairs in a dictionary - python

So let's say i have a dictionary as:

d={'a-b':[1,2,3],'c-d':[4,5,6]}

And i want to split the keys, i.e 'a-b' into two keys as 'a' and 'b', and keep same value for both etc...

So desired output should be:

{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [4, 5, 6], 'd': [4, 5, 6]}

I know i can do (Thanks to @Netwave):

d={'a-b':[1,2,3],'c-d':[4,5,6]}
newd={}
for k,v in d.items():
    x,y=k.split('-')
    newd[x]=v
    newd[y]=v
print(newd)
#{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [4, 5, 6], 'd': [4, 5, 6]}

But i don't think that's efficient,

So i am hoping one of you can give a better solution.

Upvotes: 1

Views: 688

Answers (1)

Netwave
Netwave

Reputation: 42708

Just use split once:

for k,v in d.items():
    x, y = k.split("-")
    newd[x] = v
    newd[y] = v

Or iterate through it:

for k,v in d.items():
    for new_k in k.split("-")
        newd[new_k] = v

As a dict comprehension:

{new_k : v for k,v in d.items() for new_k in k.split("-")}

Upvotes: 4

Related Questions