简体   繁体   English

将值添加到 Python 中的键字典

[英]add values to a key dictionary in Python

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在字典中的一个键中添加一些值我有这本字典的键,它是人名,它的值是 ID 号然后我决定将他们的生日添加到它的名称键中我使用了 update() 但它删除了 ID 号和用生日替换它我想添加它

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.不使用 Class 的最佳执行方式是为每个 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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