2

I have a dictionary of bigrams, obtained by importing a csv and transforming it to a dictionary:

bigram_dict = {"('key1', 'key2')": 'meaning', "('key22', 'key13')": 'mean2'}

I want keys' dictionary to be without quotation marks, i.e.:

desired_bigram_dict={('key1', 'key2'): 'meaning', ('key22', 'key13'): 'mean2'}

Would you please suggest me how to do this?

dnquixote
  • 47
  • 1
  • 6

2 Answers2

6

This can be done using a dictionary comprehension, where you call literal_eval on the key:

from ast import literal_eval
bigram_dict = {"('key1', 'key2')": 'meaning', "('key22', 'key13')": 'mean2'}

res = {literal_eval(k): v for k,v in bigram_dict.items()}

Result:

{('key22', 'key13'): 'mean2', ('key1', 'key2'): 'meaning'}
idjaw
  • 25,487
  • 7
  • 64
  • 83
3

You can literal_eval each key and reassign:

from ast import literal_eval

bigram_dict = {"('key1', 'key2')": 'meaning', "('key22', 'key13')": 'mean2'}


for k,v in bigram_dict.items():
    bigram_dict[literal_eval(k)] = v

Or to create a new dict, just use the same logic with a dict comprehension:

{literal_eval(k):v for k,v in bigram_dict.items()}

Both will give you:

{('key1', 'key2'): 'meaning', ('key22', 'key13'): 'mean2'}
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321