Home > Net >  How to store dictionary entries in a loop?
How to store dictionary entries in a loop?

Time:05-06

I've been trying to get a dictionary with tuple of strings a key of an integer out of a CSV file but am having trouble.

This is the code I have tried:

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

This is the output for this chunk of code:

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

But the output I'm looking for is more like this:

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

so that the tuples aren't numbered and also aren't in their own {}, but just in parentheses ().

CodePudding user response:

Here is a slightly different way if you want.

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

CodePudding user response:

within the function you need to set the key value pair of the dictionary like so

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

so that the full function is

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

the general syntax is

dictionary[new_key] = new_value
  • Related