如何遍历列表数组,检查每个列表中的元素并与值进行比较,以及是否与值匹配,则返回键

时间:2019-02-04 16:41:46

标签: python arrays list csv dictionary

我有一个包含数百个数组的数组,我试图遍历每个数组并测试每个数组中的元素以查看其是否存在于字典中。如果这样返回匹配值的关键。这就是我卡住的地方。这是我要完成的工作。

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]})

2 个答案:

答案 0 :(得分:1)

通过从值中搜索键,您正在错误地使用字典:应该相反。另外,对应于该值的键可能不止一个。

您的代码应在此tmeplate上:

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})

答案 1 :(得分:0)

这是我问题的解决方案:

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]})