如何在Python中更新数据字典

huangapple go评论61阅读模式
英文:

how do you update data dictionary in python

问题

I am going through a json file and extracting "name" and "id" field. I need to form a data dictionary and store "name" and "id" fields in a data dictionary called my_dict.

report = {'name': content['name'], 'id': content['id']}
print(report)

# To create and update the dictionary with report values:
my_dict.update(report)

You were getting the error because there was a typo in your code, and you were missing the curly braces when creating the report dictionary.

英文:

I am going through a json file and extracing "name" and "id" field. I need to form a data dictionary and store "name" and "id" fields in data dictionary called my_dict

report=("'name':{}, 'id':{}.format(content['name',content['id']
print(report)

'name': report1, 'id':1

I need to create and data dictionary and update the dictory with report values

I tried this:

my_dict.update(report)

I am getting this error:

ValueError: dictionary update sequence element #0 has lenght1, 2 is required

答案1

得分: 1

创建一个字典并更新该字典的报告值:

contents = [{'name': 'Ted', 'id': 1}, {'name': 'Fred', 'id': 2}]

# 空字典
my_dict = {}  

# 循环遍历contents并添加到字典
for content in contents:
    name = content['name']
    id_value = content['id']
    my_dict[name] = id_value

print(my_dict)

输出:

{'Ted': 1, 'Fred': 2}
英文:

Create a dictionary and update the dictionary with the report values:

contents = [{'name': 'Ted', 'id': 1}, {'name': 'Fred', 'id': 2}]

# empty dict
my_dict = {}  

# loop through contents and add to dict
for content in contents:
    name = content['name']
    id_value = content['id']
    my_dict[name] = id_value

print(my_dict)

Output:

{'Ted': 1, 'Fred': 2}

huangapple
  • 本文由 发表于 2023年5月18日 03:49:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定