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
好吧,您应该将“约翰”指向一个字典(或创建类来代表您的每个人(?)),因为您试图为他们保留多个代表他们的特征,并且为了使您的数据易于理解,您必须将 json 重构为这样:
info = {'John': {'id': 111111, 'birthday':'21/may/1998'},'Mike':{'id':222222,'birthday':'14/feb/1996'}}
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']}
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)
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"
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.