searchandprint
searchandprint

Reputation: 45

How can i append values to an existing key in a dictionary in python? in a loop without " "

This is my code:

names=['john', 'paul', 'george']
newdict={}

rango=input('enter a number ')

for numbers in range(0, int(rango)):

for i in names:
    newdict[i]=[]
    num = input('enter a number for the ' + str(i) + ' ')
    newdict[i].append(num)

print(newdict)

I insert this numbers

 enter a number 2
 enter a number for the john 2
 enter a number for the paul 3
 enter a number for the george 4
 enter a number for the john 5
 enter a number for the paul 6
 enter a number for the George 7

The output is the following

{'john': ['5'], 'paul': ['6'], 'george': ['7']}

but I want the following output:

{'john': [2, 5], 'paul': [3, 6], 'george': [4, 7]}

How can I get this output? Thank you very much.

Upvotes: 2

Views: 1940

Answers (2)

V. Sambor
V. Sambor

Reputation: 13389

You can also do this way:

names = ['john', 'paul', 'george']
newdict = {}
rango=input('enter a number\n')

for numbers in range(0, int(rango)):
    for name in names:
        if name not in newdict:
            newdict[name] = []

        num = input('enter a number for the ' + str(name) + ' ')
        newdict[name].append(num)

print(newdict)

Create new array only if the key is not present already.

But if is already there then you just append the new value :)

Upvotes: 1

Ratnesh
Ratnesh

Reputation: 1700

Don't do newdict[i]=[] instead check the value of the names already present or not, If not present then append it.

names=['john', 'paul', 'george']
newdict={}
rango=input('enter a number\n')
for numbers in range(0, int(rango)):
    for i in names:
        num = input('enter a number for the ' + str(i) + ' \n')
        if i in newdict:
            newdict[i].append(num)
        else:
            newdict[i] =[num]
print(newdict)

Output:

{'john': ['2', '5'], 'paul': ['3', '6'], 'george': ['4', '7']}

Upvotes: 5

Related Questions