add values to a key dictionary in Python

63 views Asked by At

Add some values in one key in a dictionary I have this dictionary with keys that it's name of persons and it's values are id number then i decided to add their birth day to it's name key I used update() but it removes the id number and replace it with birth day i want to add it

info = {'John':111111,'Mike':'222222'}

and i want to add their birth day :

info = {'John':111111,'21/may/1998','Mike':'222222','14/feb/1996'}

i don't want to add it manually

4

There are 4 answers

0
James On BEST ANSWER

You can store the values as a list or tuple.

info = {'John': [111111], 'Mike': ['222222']}
info_b = {'John':'21/may/1998','Mike':'14/feb/1996'}
for k, v in info.items():
    v.append(info_b.get(k, ''))

info
# returns:
{'John': [111111, '21/may/1998'], 'Mike': ['222222', '14/feb/1996']}
0
Yoel Nisanov On

Well, you should point 'John' to a dictionary (Or create class to represent people(?)) for every person of yours since you try to hold for them multiple features that represent them, and in order to make your data understandable you gotta reconstruct the json to be like that:

info = {'John': {'id': 111111, 'birthday':'21/may/1998'},'Mike':{'id':222222,'birthday':'14/feb/1996'}}
0
Filip On

Try making the value of each person a list

info = {"John": [111111], "Mike": [222222]}

count = 0
for item in info.values():
    birthday = input(f"{[*info.keys()][count]}'s birthday:\n")
    item.append(birthday)
    count += 1

print(info)
0
Zehef On

Dict it's all about key and value.

The best way to perform without using Class is to set the pair key/value for each Person.

Example:

#First you create two different Person
info = [{'name': "John", 'id': 111111}, {'name': "Mike", 'id': 222222}]

#If you want update the birthday of the first Person (John) you can do it like that.
info[0]["birthday"] = "21/may/1998"

#And for Mike you modify the second item in the list 
info[1]["birthday"] = "13/june/1996"