我正在尝试使用以下数据创建字典:
ListA = ['Name', 'Age', 'Gender']
ListB = ['Alex', '22', 'Male']
['Kelly','21', 'Female']
ListB来自FileB,看起来像这样:
Alex 22 Male,Kelly 21 Female
(值标签分开,组逗号分开)
预期输出:
{'Name' : 'Alex', 'Age' : '22', 'Gender' : 'Male',
'Name' : 'Kelly', 'Age': '21', 'Gender' : 'Female'
}
我尝试了以下代码:
fileB = glob.glob(filename + '.txt')
dfun = {}
ListB = []
for f in fileB:
Lines = open(f, 'r').read().split(',')
for i in Lines:
Lines2 = i.split('\t')
ListB.append(Lines2)
print(ListB) # this gives me ListB in the format above.
for i in ListB:
List1 = ['Name', 'Age', 'Gender']
List2 = i
zip1 = zip(List1,i)
zip2 = dict(zip1)
dfun.update(zip2)
print(dfun)
此代码仅将输出显示为:
{'Name' : 'Kelly', 'Age': '21', 'Gender' : 'Female'}
答案 0 :(得分:5)
您期望的输出是无效的字典,因为字典不能包含重复的键,但是,您可以使用列表推导并将字典值存储为列表中的元素:
ListA = ['Name', 'Age', 'Gender']
ListB = [['Alex', '22', 'Male'], ['Kelly','21', 'Female']]
result = [dict(zip(ListA, i)) for i in ListB]
输出:
[{'Name': 'Alex', 'Age': '22', 'Gender': 'Male'}, {'Name': 'Kelly', 'Age': '21', 'Gender': 'Female'}]
编辑:
result = {a:[k[i] for k in ListB] for i, a in enumerate(ListA)}
输出:
{'Name': ['Alex', 'Kelly'], 'Age': ['22', '21'], 'Gender': ['Male', 'Female']}