简体   繁体   中英

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.

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']}

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM