Add dictionary item in list to a dictionary - python

Hi guys I'm pretty lost with this simple problem. I have a dictionary and a list of dictionaries in python and I want to loop over the list to add each dictionary to the first dictionary but somehow it just adds the last dictionary with the solution I came up with. I'm using Python 3.6.5
This is what I've tried:
res = []
dictionary = {"id": 1, "name": "Jhon"}
dictionary_2 = [
{"surname": "Doe", "email": "jd#example.com"},
{"surname": "Morrison", "email": "jm#example.com"},
{"surname": "Targetson", "email": "jt#example.com"}
]
for info in dictionary_2:
aux_dict = dictionary
aux_dict["extra"] = info
res.append(aux_dict)
print(res)
What I expect is:
[{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Doe', 'email': 'jd#example.com'}},
{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Morrison', 'email': 'jm#example.com'}},
{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt#example.com'}}]
And this is what I get
[{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt#example.com'}},
{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt#example.com'}},
{'id': 1, 'name': 'Jhon', 'extra': {'surname': 'Targetson', 'email': 'jt#example.com'}}]
This is probably a duplicate of some other question but I can't manage to find it

This is because you keep adding the same aux_dict to res.
What you probably want to do is make a copy of dictionary; just assigning it to aux_dict does not make a copy.
This is how you make a (shallow) copy:
aux_dict = dictionary.copy()
That would be sufficient in your case.

You can achieve this in one line using list comprehension and dict constructor:
dictionary = {"id": 1, "name": "Jhon"}
dictionary_2 = [
{"surname": "Doe", "email": "jd#example.com"},
{"surname": "Morrison", "email": "jm#example.com"},
{"surname": "Targetson", "email": "jt#example.com"}
]
# ...
res = [dict(dictionary, extra=item) for item in dictionary_2]
# ...
print(res)

Related

Populating a dict with for loop from a list

Hello I have the following list :
Info_Types = [
{'name': 'A'},
{'name': 'B'},
{'name': 'C'}
]
Next, I would like to use this list with a loop in this type of dictionary:
{
"name": Info_Types[i]['name'],
"domainId": "c50d7ff8-0e6d-4132-a528-f286781f017b",
"typeId": "1bf1b4ac-f52f-4ff9-be43-f96d76dff4c1",
"statusId": "00000000-0000-0000-0000-000000005008",
"excludedFromAutoHyperlinking": 'true'
}
The result I want to get is the following:
[{'name': 'A',
'domainId': 'c50d7ff8-0e6d-4132-a528-f286781f017b',
'typeId': '1bf1b4ac-f52f-4ff9-be43-f96d76dff4c1',
'statusId': '00000000-0000-0000-0000-000000005008',
'excludedFromAutoHyperlinking': 'true'},
{'name': 'B',
'domainId': 'c50d7ff8-0e6d-4132-a528-f286781f017b',
'typeId': '1bf1b4ac-f52f-4ff9-be43-f96d76dff4c1',
'statusId': '00000000-0000-0000-0000-000000005008',
'excludedFromAutoHyperlinking': 'true'},
{'name': 'C',
'domainId': 'c50d7ff8-0e6d-4132-a528-f286781f017b',
'typeId': '1bf1b4ac-f52f-4ff9-be43-f96d76dff4c1',
'statusId': '00000000-0000-0000-0000-000000005008',
'excludedFromAutoHyperlinking': 'true'}]
My idea is that I need to use a for loop but I don't really know how to build it. Someone can help me? thanks
It's better to use list comprehension:
result = [
{
"name": name,
"domainId": "c50d7ff8-0e6d-4132-a528-f286781f017b",
"typeId": "1bf1b4ac-f52f-4ff9-be43-f96d76dff4c1",
"statusId": "00000000-0000-0000-0000-000000005008",
"excludedFromAutoHyperlinking": 'true'
}
for name in Info_Types
]

Python steamlit select box menu returns string, but I need dict or list

Stack on this case, Python steamlit select box menu returns string, but I need dict or list, to use it further in my code.
I want to see company1, company2, company3 in dropdown menu, and if user's choice was for example 'company2' get ['ID': 'zxc222’, 'NAME': 'company2','DESC': 'comp2'].
BaseObject = [{
'ID': 'zxc123',
'NAME': 'company1',
'DESC': 'comp1'
}, {
'ID': 'zxc222',
'NAME': 'company2',
'DESC': 'comp2'
}, {
'ID': 'zxc345',
'NAME': 'company3',
'DESC': 'comp3'
}]
lenbo = len(BaseObject)
options = []
for i in range(0, lenbo):
options.append((BaseObject[i])['NAME'])
st.selectbox('Subdivision:', options)
You can do the conversion to a dict after the selectbox:
import streamlit as st
BaseObject = [{
'ID': 'zxc123',
'NAME': 'company1',
'DESC': 'comp1'
}, {
'ID': 'zxc222',
'NAME': 'company2',
'DESC': 'comp2'
}, {
'ID': 'zxc345',
'NAME': 'company3',
'DESC': 'comp3'
}]
lenbo = len(BaseObject)
options = []
for i in range(0, lenbo):
options.append((BaseObject[i])['NAME'])
choice = st.selectbox('Subdivision:', options)
chosen_base_object = None
for base_object in BaseObject:
if base_object["NAME"] == choice:
chosen_base_object = dict(base_object)
print(chosen_base_object) # {'ID': 'zxc345', 'NAME': 'company3', 'DESC': 'comp3'}

Assigning attributes to array of objects based on object array lookup

I have this code block that assigns an account type based on a list of acccount names. But it fails if an account name is not in any of the 'name' arrays.
How do I add a "default" type if not found? Or is there a more elegant way to do this?
accts = [
{'id': 1425396, 'name': 'Banana'},
{'id': 1425399, 'name': 'Schwab Brokerage'},
{'id': 1425400, 'name': 'Schwab'},
{'id': 1425411, 'name': 'CapitalOne'},
{'id': 1425428, 'name': '401K'},
{'id': 1425424, 'name': 'Venmo'},
{'id': 1425428, 'name': 'Geico'},
{'id': 1425428, 'name': 'PayPal'},
{'id': 1426349, 'name': 'Coinbase'},
{'id': 1426349, 'name': 'XXX'}
]
for acct in accts: acct['acct_type'] = next(acct_type for acct_type in
[
{'acct_type':'checking', 'accts':['Schwab','Venmo']},
{'acct_type':'credit', 'accts':['Banana','CapitalOne']},
{'acct_type':'other', 'accts':['Geico','PayPal']},
{'acct_type':'invest', 'accts':['Schwab Brokerage','401K','Coinbase']}
]
if acct['name'] in acct_type['accts'])['acct_type']
The last (XXX) account causes this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
You could simply replace the list-of-dicts lookup with a dictionary. For example:
acct_types = {
"Schwab": "checking", "Venmo": "checking",
"Banana": "credit", "CapitalOne": "credit",
"Geico": "other", "PayPal": "other",
"Schwab Brokerage": "invest", "401K": "invest", "Coinbase": "invest"
}
Then, all you need to do is lookup in this dictionary using the .get() function. The second argument provides the default value.
for acct in accts:
acct['acct_type'] = acct_types.get(acct['name'], "other")
Which gives the expected result:
[{'id': 1425396, 'name': 'Banana', 'acct_type': 'credit'},
{'id': 1425399, 'name': 'Schwab Brokerage', 'acct_type': 'invest'},
{'id': 1425400, 'name': 'Schwab', 'acct_type': 'checking'},
{'id': 1425411, 'name': 'CapitalOne', 'acct_type': 'credit'},
{'id': 1425428, 'name': '401K', 'acct_type': 'invest'},
{'id': 1425424, 'name': 'Venmo', 'acct_type': 'checking'},
{'id': 1425428, 'name': 'Geico', 'acct_type': 'other'},
{'id': 1425428, 'name': 'PayPal', 'acct_type': 'other'},
{'id': 1426349, 'name': 'Coinbase', 'acct_type': 'invest'},
{'id': 1426349, 'name': 'XXX', 'acct_type': 'other'}]
If you don't want to manually create the acct_types dictionary, you can easily convert the list-of-dicts that you already have:
lookup = [
{'acct_type':'checking', 'accts':['Schwab','Venmo']},
{'acct_type':'credit', 'accts':['Banana','CapitalOne']},
{'acct_type':'other', 'accts':['Geico','PayPal']},
{'acct_type':'invest', 'accts':['Schwab Brokerage','401K','Coinbase']}
]
acct_types = dict()
for item in lookup:
for acct_name in item['accts']:
acct_types[acct_name] = item['acct_type']
I figured it out, using the default parameter of next():
for acct in accts: acct['acct_type'] = next(
(
acct_type for acct_type in
[
{'acct_type':'checking', 'accts':['Schwab','Venmo']},
{'acct_type':'credit', 'accts':['Banana','CapitalOne']},
{'acct_type':'other', 'accts':['Geico','PayPal']},
{'acct_type':'invest', 'accts':['Schwab Brokerage','401K','Coinbase']}
]
if acct['name'] in acct_type['accts']
),
{'acct_type':'other'}
)['acct_type']

Retrieve only certain keys and values from a dictionary, nested inside a list

I've been stuck on this for hours.. I want to retrieve only ONE individuals keys and values from a dictionary that is nested inside of a list.
GAMERS = [{
'name': 'Fatboi',
'parent': 'Dick Van Dyke',
'game': 'Dark Souls 3',
'weight': '420 lbs'
},
{
'name': 'Justin',
'parent': 'Heather Blueberry',
'game': 'Tetris',
'weight': '180 lbs'
},
{
'name': 'jerkhead',
'parent': 'none',
'games': 'Hello Kitty',
'weight': '240 lbs'
},{
'name': 'Tumor',
'parent': 'Jack Black',
'games': 'Trying to live',
'weight': '150 lbs'
}]
So for instance I want to get Justins information printed only, nobody elses. Any insights?
You can pass the key which you want and push it to separate list.
GAMERS = [{
'name': 'Fatboi',
'parent': 'Dick Van Dyke',
'game': 'Dark Souls 3',
'weight': '420 lbs'
},
{
'name': 'Justin',
'parent': 'Heather Blueberry',
'game': 'Tetris',
'weight': '180 lbs'
},{
'name': 'jerkhead',
'parent': 'none',
'games': 'Hello Kitty',
'weight': '240 lbs'
}]
def get_key_pair_list(input_dict, key):
new_list = []
for item in input_dict:
my_dict = {}
if key in item.keys():
my_dict[key] = item[key]
new_list.append(my_dict)
return new_list
print(get_key_pair_list(GAMERS, 'name'))
Output:
[{'name': 'Fatboi'}, {'name': 'Justin'}, {'name': 'jerkhead'}]
Comprehensive way:
key = 'name'
my_list = [{key, item[key]} for item in GAMERS if key in item.keys() ]
print(my_list)
output:
[{'name', 'Fatboi'}, {'name', 'Justin'}, {'name', 'jerkhead'}]
You want to filter the list and grab the first value that matches a predicate. Make sure to handle the case where the item doesnt exist!
filtered_info = (
item for item in GAMERS if item['name'] == 'Justin'
)
justin_info = next(filtered_info, None)
if justin_info is not None:
print(justin_info)

There are 2 dictionaries, I want to append the matching keys from second dictionaries and store them as a list f dictionaries in the parent dictionary

For example, I have below 2 dictionaries,
dict1 = [{'id': 1, 'name': 'BOB'}, {'id': 2, 'name': 'DOD'}]
dict2 = [{'idd': 1, 'comp': 'BB', }, {'idd': 1, 'work': 'pent'}, {'idd': 2, 'comp': 'DD'}]
And I want below output -
dict1 = [
{
'id': 1,
'name': 'BOB',
'Details:[
{
'idd': 1,
'comp': 'BB'
},
{
'idd': 1,
'work': 'pent'
}
]
},
{
'id': 2,
'name': 'DOD',
'Details':[
{
'idd': 2,
'comp': 'DD'
}
]
}
]
I want to get the above result, using dictionary zip or ordereddict
Convert the dict1 to a real dict, with the id as key, and add an empty Details list to each entry. Then, iterate dict2 and and the missing elements.
dict1 = {item['id']: {**item, **{'Details': []}} for item in dict1}
for item in dict2:
item = dict(item)
_id = item.pop('idd')
temp[_id]['Details'].append(item)
dict1 = [item for item in dict1.values()]

Categories

Resources