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


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']:
        names = {
            doc['staticAssignedDriver']['name']: doc['id']

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

<class 'dict'>
<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



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'},
d = {}
for dct in x:
    d.update({key: value for key, value in dct.items()})

{'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.