mCs
mCs

Reputation: 2921

Python3: change dictionary key from string to tuple of strings

Say I got a dict:

{'I like': 14, 'you like': 12, 'he likes': 2}

I would like to change into to be like:

{('I', 'like'):14, ('you', 'like'):12. ('he','likes'):2}

So I want to change keys of the dict form strings to tuple of strings. I tried to make it:

from ast import literal_eval as make_tuple
...    
d = {make_tuple(k): d[k] for k in d}

but I got:

  File "/usr/lib/python3.5/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    of the
         ^

What is the most efficient way to do this?

Upvotes: 0

Views: 1823

Answers (4)

Aaditya Ura
Aaditya Ura

Reputation: 12679

You can do with two ways:

Data:

your_data={'I like': 14, 'you like': 12, 'he likes': 2}

One line solution:

print({tuple(key.split()):value for key,value in your_data.items()})

output:

{('I', 'like'): 14, ('he', 'likes'): 2, ('you', 'like'): 12}

Detailed solution:

Above dict comprehension is same as :

final_dict={}
for key,value in your_data.items():
    final_dict[tuple(key.split())]=value

print(final_dict)

output:

{('I', 'like'): 14, ('he', 'likes'): 2, ('you', 'like'): 12}

Upvotes: 1

Pablo Arias
Pablo Arias

Reputation: 380

You can solve this using a dictionary comprehension:

>>> original = {'I like': 14, 'you like': 12, 'he likes': 2}
>>> new_d = {tuple(k.split()): v for k,v in original.items()}
>>> new_d
{('I', 'like'): 14, ('you', 'like'): 12, ('he', 'likes'): 2}

Upvotes: 1

Reblochon Masque
Reblochon Masque

Reputation: 36702

You can do this in a dictionary comprehension:

d = {'I like': 14, 'you like': 12, 'he likes': 2}
new_d = {tuple(k.split()): v for k, v in d.items()}

new_d

output:

{('I', 'like'): 14, ('he', 'likes'): 2, ('you', 'like'): 12}

Upvotes: 2

quamrana
quamrana

Reputation: 39404

You just need the builtin tuple():

source = {'I like': 14, 'you like': 12, 'he likes': 2}

target = { tuple(k.split()):source[k] for k in source}

print(target)

Output:

{('I', 'like'): 14, ('you', 'like'): 12, ('he', 'likes'): 2}

p.s.

Don't use dict as a variable name.

Upvotes: 4

Related Questions