如何在循环中存储字典条目?

How to store dictionary entries in a loop?

我一直在尝试从 CSV 文件中获取包含字符串元组和整数键的字典,但遇到了问题。

这是我试过的代码:

fullcsv = [['Brand', 'Swap', 'Candy1', 'Candy2', 'Capacity'],
           ['Willywonker', 'Yes', 'bubblegum', 'mints', '7'],
           ['Mars-CO', 'Yes', 'chocolate', 'bubblegum', '1'],
           ['Nestle', 'Yes', 'bears', 'bubblegum', '2'],
           ['Uncle Jims', 'Yes', 'chocolate', 'bears', '5']]

def findE(fullcsv):
    i = 0
    a = {}
    while i < len(fullcsv)-1:
        i = i + 1
        a[i] = ({(fullcsv[i][2],fullcsv[i][3]): int(fullcsv[i][4])})
    return a

这是这段代码的输出:

{1: {('bubblegum', 'mints'): 7},
 2: {('chocolate', 'bubblegum'): 1},
 3: {('bears', 'bubblegum'): 2},
 4: {('chocolate', 'bears'): 5}}

但我正在寻找的输出更像这样:

{('bubblegum', 'mints'): 7,
 ('chocolate', 'bubblegum'): 1,
 ('bears', 'bubblegum'): 2,
 ('chocolate', 'bears'): 5}

这样元组就没有编号,也不在它们自己的 {} 中,而是在括号 ().

在函数中你需要像这样设置字典的键值对

a[(fullcsv[i][2],fullcsv[i][3])] = int(fullcsv[i][4])

这样完整的功能就是

def findE(fullcsv):
    i = 0
    a ={}
    while i < len(fullcsv)-1:
        i = i + 1
        a[(fullcsv[i][2],fullcsv[i][3])] = int(fullcsv[i][4])
            
    return a

一般语法是

dictionary[new_key] = new_value

如果你愿意,这里有一个稍微不同的方法。

def findE(fullcsv):
    new_dict = {}
    for entry in fullcsv[1:]:
        new_dict[(entry[2],entry[3])] = entry[-1]
    return new_dict