-3

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
user1471980
  • 10,127
  • 48
  • 136
  • 235
  • 1
    You need to add more clarity. `print(report)` looks strange/incorrect, you'll need to explain what it is. (Is it a `list` of `dict`?) What is `my_dict` beforehand? What do you expect `my_dict` to be afterwards? – Kache May 17 '23 at 19:53
  • `report` seems to be a string, not a dict; if this is confirmed, `my_dict.update(ast.literal_eval('{' + report + '}'))` should work. – Swifty May 17 '23 at 19:59
  • @Swifty ast.literal_eval? NameError: name 'ast' is not defined – user1471980 May 17 '23 at 20:02
  • In your original post, you have multiple identical keys. Keys must be unique. Also, to create a dictionary: `report = {"name": content["name"], "id": content["id"]}`. – 001 May 17 '23 at 20:02
  • That said, your formatted string seems strange. And what is `content` ? – Swifty May 17 '23 at 20:07

1 Answers1

1

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}
Captain Caveman
  • 1,448
  • 1
  • 11
  • 24