Can I combine multiple dicts with the same name in Python?

Question:

I’m trying to create a new list from an API return in python. The purpose of this API call is to pull a list of driver’s names, and pair them to a vehicle ID native to the API service. The code currently looks like this:

url = url

headers = {
    "accept": "application/json",
    "authorization": auth
}

response = requests.get(url, headers=headers)
response = response.json()
for doc in response['data']:
    try:
        doc['id'],
        doc['staticAssignedDriver']['name']
    except:
        pass
    else:
        names = {
            doc['staticAssignedDriver']['name']: doc['id']
        }
        names.update(names)
        print(type(names))
        print(names)

This prints a list of unique names and id’s as individual dicts. IE:

{'name1':'id1'}
<class 'dict'>
{'name2':'id2'}
<class 'dict'>

Until I have all of my name:id pairs from my API.

But I’d like to make that a single dict, as such:

{'name1': 'id1', 'name2': 'id2'}

It seems like each new name/id pair ends up being its own var ‘names’. Is there a way to make this its own singular dict, instead of individual?

Asked By: Kouu_Tori

||

Answers:

When you do names = {whatever: whatever}, you always create a new dictionary with exactly one key and value. If you want to have only one dictionary that you update over and over, create the dictionary outside of the loop, and just assign a single value into it at a time:

names = {}

for doc in ...:
   ...
   names[doc['staticAssignedDriver']['name']] = doc['id']
Answered By: Blckknght
x = [{'name1':'id1'},
    {'name2':'id2'}]
d = {}
for dct in x:
    d.update({key: value for key, value in dct.items()})

print(d)
{'name1': 'id1', 'name2': 'id2'}
Answered By: CrookedNoob
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.