英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论