自动将键值对附加到字典

Append a key-value pair to a dict automatically

如何自动将键值对添加到字典中?例如,我有一个非常长的希腊语单词文件,以及英文翻译(用“;”分隔):这重复了很多行,我想把每一行(由“Greek;”组成)翻译”)在词典中。 我给你举个例子:

αἰτέω;ask;beg
αἰτία;responsibility
αἰτιάομαι;accuse;censure

我想要:

dict = {'αἰτέω': 'ask, beg', 'αἰτία': 'responsibility', 'αἰτιάομαι': 'accuse, censure'}

另一个例子可以是:

a bow;un inchino
a cloaklet;un mantello
a coaxing;un lusinghiero

我想要:

dict = {'a bow': 'un inchino', 'a cloaklet': 'un mantello', 'a coaxing': 'un 
        lusinghiero'}

你能帮帮我吗?

一个非常简单的方法就是用'\n'分割然后分割';'为了

text= 'αἰτέω;ask;beg\nαἰτία;responsibility\nαἰτιάομαι;accuse;censure'.split('\n')
result = dict()
for t in text:
     t = t.split(';')
     result[t[0]]  = t[1]
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from pprint import pprint

lines = """αἰτέω;ask;beg
αἰτία;responsibility
αἰτιάομαι;accuse;censure
a bow;un inchino
a cloaklet;un mantello
a coaxing;un lusinghiero"""

d = {
    line.split(";")[0] : ", ".join(line.split(";")[1:])
    for line in lines.splitlines()
}

pprint(d)

结果:

{'a bow': 'un inchino',
 'a cloaklet': 'un mantello',
 'a coaxing': 'un lusinghiero',
 'αἰτέω': 'ask, beg',
 'αἰτία': 'responsibility',
 'αἰτιάομαι': 'accuse, censure'}

使用 dict 理解不要使用 dict 作为变量名:

s='''αἰτέω;ask;beg
αἰτία;responsibility
αἰτιάομαι;accuse;censure'''
mydict = {x.split(';')[0]: ', '.join(x.split(';')[1:])for x in s.split()}

如果你有一个 csv 文件,你最终是这个意思?

def csv_dict_list(variables_file):
    reader = csv.DictReader(open(variables_file, 'rb'))
    dict_list = []
    for line in reader:
        dict_list.append(line)
    return dict_list