我有一个bigrams字典,通过导入csv并将其转换为字典获得:
bigram_dict = {"('key1', 'key2')": 'meaning', "('key22', 'key13')": 'mean2'}
我希望密钥'字典没有引号,即:
desired_bigram_dict={('key1', 'key2'): 'meaning', ('key22', 'key13'): 'mean2'}
请你建议我怎么做?
答案 0 :(得分:6)
这可以使用字典理解来完成,您可以在密钥上调用literal_eval:
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()}
结果:
{('key22', 'key13'): 'mean2', ('key1', 'key2'): 'meaning'}
答案 1 :(得分:3)
您可以literal_eval每个密钥并重新分配:
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
或者要创建一个新的dict,只需使用与 dict理解相同的逻辑:
{literal_eval(k):v for k,v in bigram_dict.items()}
两者都会给你:
{('key1', 'key2'): 'meaning', ('key22', 'key13'): 'mean2'}