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

Time:01-28

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 list, 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?

CodePudding user response:

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']

CodePudding user response:

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

CodePudding user response:

Yes, you can combine multiple dictionaries with the same name in Python by using the update() method on a dictionary. In your current code, you are creating a new dictionary with the same variable name on each iteration of the loop, which is overwriting the previous one and only keeping the last one.

Instead of creating a new dictionary on each iteration, you can create an empty dictionary before the loop and then update it with the new name:id pair on each iteration. Here's an example of how you can change your code to achieve this:

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

This will create an empty dictionary names before the loop, and on each iteration, it will add the new name:id pair to the existing dictionary using the update() method. This way, you will end up with a single dictionary containing all the name:id pairs, instead of a list of individual dictionaries.

  • Related