2

I'm having some issues trying to create a dictionary from 2 lists.

I'm trying to get this as output.

{1: {'name1', 'age1'}, 2: {'name2', 'age2'}, 3: {'name3', 'age3'}}

My current code: (I'm new to coding so this is a mess and very efficient, and yes I do realize I'm running all code below 5 times)

def Update():
    for r in range(1,5):
        v1list.append(StringVar())
        v2list.append(StringVar())
        NameEntry = Entry(root, textvariable=v1list[r-1]).grid(row = r, column = 0, sticky=W)
        AgeEntry = Entry(root, textvariable=v2list[r-1]).grid(row = r, column = 4, sticky=W)
        for var1, var2 in ((a,b) for a in v1list for b in v2list):
            UserInput[r] = {var1.get(), var2.get()}
            print(UserInput)

The output keeps pushing var1 and var2 forward resulting in this as output:

{1: {''}, 2: {''}, 3: {''}, 4: {''}}

I do actually see all inputs in there they just keep moving forward in the dictionary.

sacuL
  • 49,704
  • 8
  • 81
  • 106

2 Answers2

2

Try creating the dictionary through a dictionary comprehension:

names = ['name1', 'name2', 'name3']
ages = ['age1', 'age2', 'age3']

name_age_dict = {i+1:{names[i],ages[i]} for i in range(len(names))}

>>> name_age_dict
{1: {'age1', 'name1'}, 2: {'name2', 'age2'}, 3: {'age3', 'name3'}}

It's cleaner than a for loop, and remains readable. Essentially, it goes through each item in your lists (assuming the lists have the same length), and creates a dictionary of {name, age} for each item in each list, assigning the index number (+1 to skip over the 0) as the key for that dictionary.

Some new python users have a difficult time with the list and dict comprehension syntax, so if you prefer to see it as a loop, this achieves the same thing:

name_age_dict = {}

for i in range(len(names)):
    name_age_dict[i+1] = {names[i], ages[i]}

>>> name_age_dict
{1: {'age1', 'name1'}, 2: {'name2', 'age2'}, 3: {'age3', 'name3'}}
sacuL
  • 49,704
  • 8
  • 81
  • 106
0

Hope this solves your issue.

    d = {}
    names=['name1','name2','name3','name4','name5']
    age=[1,2,3,4,5]
    for i in range(1,6):
        d[str(i)]={}
        d[str(i)][names[i-1]]=age[i-1]
    print(d)
Abhisek Roy
  • 582
  • 12
  • 31