Search code examples
pythondata-dictionary

how do you update data dictionary in python


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

Solution

  • 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}