我有一个数组持有数百阵列,我通过每个阵列试图循环和每个阵列中测试的元素,看它是否在字典中存在。如果这样返回匹配值的关键。下面是我在哪里卡住了。下面有什么,我试图完成。
dictionary = {'Bob' : '1', 'John' : '2', 'Andy': '3'}
list = [['5','2019','$50'],['1','2019','$50'],['5','2018','$50']
with open('C:/...','w',newline='') as f:
fieldName = ['ID','Name','Price']
writer = csv.DictWriter(f, fieldnames=fieldName)
writer.writeheader()
for i in list:
if i[0] in dictionary.values():
writer.writerow({'ID' : i[0], 'Name' : *DictionaryKey*, 'Price' : i[2]})
你被搜索的键的值作出错误使用您的dictionnay的:它应该是相反的。另外有可能是与该值对应一个以上的按键。
您的代码应该是这个模板:
dictionary = {'1': 'Bob', '2': 'John', '3': 'Andy'}
my_list = [['5','2019','$50'],['1','2019','$50'],['5','2018','$50'] # do not use 'list' as variable name
with open('C:/...','w+',newline='') as f:
fieldNames = ['ID','Name','Price']
writer = csv.DictWriter(f, fieldnames=fieldNames)
writer.writeheader()
for id_, year, price in my_list:
if id_ in dictionary.values():
writer.writerow({'ID' : id_, 'Name' : dictionary[id_], 'Price' : price})
这是解决我的问题:
dictionary = {'1' : 'Bob', '2' : 'John', '2': 'Andy'}
my_list = [['5','2019','$50'],['1','2019','$50'],['5','2018','$50']]
with open('C:/...','w',newline='') as f:
fieldName = ['ID','Name','Price']
writer = csv.DictWriter(f, fieldnames=fieldName)
writer.writeheader()
for i in list:
for key, value in dictionary:
if i[0] == key:
writer.writerow({'ID' : i[0], 'Name' : key, 'Price': i[2]})