Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to store dictionary entries in a loop?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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 ().

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading