Updating dictionaries of list from another dictionary python - python

I have two list of dictionaries: I am trying to compare test2 with test1 and update accordingly.
test1 = [{'names': ['a', 'b', 'c'],
'country': 'USA',
'state': 'Texas'},
{'names': ['d', 'e', 'f'],
'country': 'Australia',
'state': 'Melbourne'},
{'names': ['i', 'j', 'k'],
'country': 'canada',
'state': 'Toronto'},
{'names': ['l', 'm', 'n'],
'country': 'Austria',
'state': 'Burgenland'}]
test2 = [{'code': 4286,
'list_of_countries': ['USA',
'Australia',
'Colombia',
'Denmark',
'Greece',
'Iceland']},
{'code':4287,
'list_of_countries': ['Texas',
'Argentina',
'Austria',
'Bangladesh', 'canada']}]
Expected Output:
test2 = [{'names':['a', 'b', 'c', 'd', 'e', 'f'],
'country': ['USA', 'Australia'],
'state': ['Texas', 'Melbourne'],
'code':4286},
{'names':['i', 'j', 'k', 'l', 'm', 'n'],
'country': ['canada', 'Austria'],
'state': ['Toronto','Burgenland'],
'code':4287}]
Tried below snippet: By searching the test1 country in test2 list_of_countries:
for i in test1:
for j in test2:
a = []
if i.get('country') in j.get('list_of_countries'):
a.append({'country':i.get('country'), 'state':i.get('state'})
j.update(a)

You can transform test2 to a dictionary, associating each entry in list_of_countries with their proper key. Then, you can use this result for grouping:
test2 = [{'code': 4286, 'list_of_countries': ['USA', 'Australia', 'Colombia', 'Denmark', 'Greece', 'Iceland']}, {'code': 4287, 'list_of_countries': ['Texas', 'Argentina', 'Austria', 'Bangladesh', 'canada']}]
test1 = [{'names': ['a', 'b', 'c'], 'country': 'USA', 'state': 'Texas'}, {'names': ['d', 'e', 'f'], 'country': 'Australia', 'state': 'Melbourne'}, {'names': ['i', 'j', 'k'], 'country': 'canada', 'state': 'Toronto'}, {'names': ['l', 'm', 'n'], 'country': 'Austria', 'state': 'Burgenland'}]
d = {i:k['code'] for k in test2 for i in k['list_of_countries']}
Now, you can create a series of defaultdicts associated with the country code. By looping over the country/state dicts in test1, you can keep a running update of the states and countries that are associated with each code:
from collections import defaultdict
new_d = dict(zip(d.values(), [defaultdict(list) for _ in d]))
for i in test1:
for a, b in i.items():
new_d[d[i['country']]][a].append(b)
r = [{'code':a, **b, 'names':[j for k in b['names'] for j in k]} for a, b in new_d.items()]
The final list comprehension transforms new_d to your desired format, a list of dictionaries.
Output:
[{'code': 4286, 'names': ['a', 'b', 'c', 'd', 'e', 'f'], 'country': ['USA', 'Australia'], 'state': ['Texas', 'Melbourne']}, {'code': 4287, 'names': ['i', 'j', 'k', 'l', 'm', 'n'], 'country': ['canada', 'Austria'], 'state': ['Toronto', 'Burgenland']}]

Related

Excel vlookup in python dataframe

How can i make vlookup like in excel to pandas, i'm totally begginer in python. My first and second dataframe like this
data_01 = pd.DataFrame({'Tipe Car':['A', 'B', 'C', 'D'], 'Branch':['UD', 'UA', 'UK', 'UA'], 'Area':['1A', '1B', '1C', '1D']})
data_02 = pd.DataFrame({'Tipe Car':['A', 'B', 'E', 'F'], 'Branch':['UD', 'UA', 'UK', 'UA']})
and then expected output is
data_03 = pd.DataFrame({'Tipe Car':['A', 'B', 'E', 'F'], 'Branch':['UD', 'UA', 'UK', 'UA'], 'Area':['1A', '1B', 'NaN', 'NaN']})
Use pandas.DataFrame.join
import pandas as pd
df1 = pd.DataFrame({'Tipe Car':['A', 'B', 'C', 'D'], 'Branch':['UD', 'UA', 'UK', 'UA'], 'Area':['1A', '1B', '1C', '1D']})
df2 = pd.DataFrame({'Tipe Car':['A', 'B', 'E', 'F'], 'Branch':['UD', 'UA', 'UK', 'UA']})
df1.set_index('Tipe Car').join(df2.set_index('Tipe Car'), how='right', lsuffix='_df1', rsuffix='_df2')
>>>
Branch_df1 Area Branch_df2
Tipe Car
A UD 1A UD
B UA 1B UA
E NaN NaN UK
F NaN NaN UA

how to get all value in list in same time

following show the my list value (variable is "data")
[{'letters': ['R', 'V', 'X', 'U', 'M', 'Z', 'B', 'O', 'R'],
'words': ['RVX', 'BOM', 'RUB', 'RUZ', 'MBOOO', 'RMR'],
'score': 51},
{'letters': ['P', 'X', 'M', 'R', 'D', 'S', 'I', 'C', 'E'],
'words': ['PXM', 'RDS', 'ICE', 'PRI', 'DSCE', 'PXM', 'MRE'],
'score': 54}]
Then I used the following code
print(*data)
output was
{'letters': ['R', 'V', 'X', 'U', 'M', 'Z', 'B', 'O', 'R'], 'words': ['RVX', 'BOM', 'RUB', 'RUZ', 'MBOOO', 'RMR'], 'score': 51} {'letters': ['P', 'X', 'M', 'R', 'D', 'S', 'I', 'C', 'E'], 'words': ['PXM', 'RDS', 'ICE', 'PRI', 'DSCE', 'PXM', 'MRE'], 'score': 54}
but I want to get that output with comma with saparate two JSON
Like this
{'letters': ['R', 'V', 'X', 'U', 'M', 'Z', 'B', 'O', 'R'], 'words': ['RVX', 'BOM', 'RUB', 'RUZ', 'MBOOO', 'RMR'], 'score': 51},
{'letters': ['P', 'X', 'M', 'R', 'D', 'S', 'I', 'C', 'E'], 'words': ['PXM', 'RDS', 'ICE', 'PRI', 'DSCE', 'PXM', 'MRE'], 'score': 54}
Any one can help me
Thank you
Is this what you are trying to accomplish?
print(*data, sep=",\n")
That will put your items on separate lines, with commas after all but the last.
You can try this:
print(*data, sep=',')

creating a list of dictionaries from pandas dataframe

This is my df:
df = pd.DataFrame({'sym': ['a', 'b', 'c', 'x', 'y', 'z', 'q', 'w', 'e'],
'sym_t': ['tsla', 'msft', 'f', 'aapl', 'aa', 'gg', 'amd', 'ba', 'c']})
I want to separate this df into groups of three and create a list of dictionaries:
options = [{'value':'a b c', 'label':'tsla msft f'}, {'value':'x y z', 'label':'aapl aa gg'}, {'value':'q w e', 'label':'amd ba c'}]
How can I create that list? My original df has over 1000 rows.
Try groupby to concatenate the rows, then to_dict:
tmp = df.groupby(np.arange(len(df))//3).agg(' '.join)
tmp.columns = ['value', 'label']
tmp.to_dict(orient='records')
Output:
[{'value': 'a b c', 'label': 'tsla msft f'},
{'value': 'x y z', 'label': 'aapl aa gg'},
{'value': 'q w e', 'label': 'amd ba c'}]

How to add a variable to a dictionary in Python?

I want to add on to my current dictionary without hard-coding. I want to distinguish between stores by adding on -A and -B based on the station someone is working in.
a_dict = {'A': [['LA', 'Sallys', 'Associate '], ['Hollywood', 'Tonys', 'Shelf'], ['Compton', 'Sally', 'Shelves']],'B': [['SAC', 'Sallys', 'Associate '], ['Townsland', 'Tonys', 'Shelf'], ['Compton', 'Tiffanys', 'Shelves']]}
b_dict = {'Site':"", 'Store':"", 'Station':""}
for key in a_dict:
b_dict.update(a_dict)
#print(b_dict[key[0]])
#print(value[0])
output = [
{'Site':val[0][0], 'Store':val[1][1], 'Station':val[2]}
for vals in a_dict.values()
for val in vals
]
print(output)
The code currently prints out this:
[{'Site': 'L', 'Store': 'a', 'Station': 'Associate '}, {'Site': 'H', 'Store': 'o', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'a', 'Station': 'Shelves'}, {'Site': 'S', 'Store': 'a', 'Station': 'Associate '}, {'Site': 'T', 'Store': 'o', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'i', 'Station': 'Shelves'}]
[{'Site': 'L', 'Store': 'a', 'Station': 'Associate '}, {'Site': 'H', 'Store': 'o', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'a', 'Station': 'Shelves'}, {'Site': 'S', 'Store': 'a', 'Station': 'Associate '}, {'Site': 'T', 'Store': 'o', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'i', 'Station': 'Shelves'}]
But I want it to print out this:
[{'Site': 'L', 'Store': 'a-A', 'Station': 'Associate '}, {'Site': 'H', 'Store': 'o-B', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'a-B', 'Station': 'Shelves'}, {'Site': 'S', 'Store': 'a-A', 'Station': 'Associate '}, {'Site': 'T', 'Store': 'o-B', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'i-B', 'Station': 'Shelves'}]
[{'Site': 'L', 'Store': 'a-A', 'Station': 'Associate '}, {'Site': 'H', 'Store': 'o-B', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'a-B', 'Station': 'Shelves'}, {'Site': 'S', 'Store': 'a-A', 'Station': 'Associate '}, {'Site': 'T', 'Store': 'o-B', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'i-B', 'Station': 'Shelves'}]
So like if the associate is shelf or shelves than the store would be -B if not the store should be -A.
Here you go.
a_dict = {'A': [['LA', 'Sallys', 'Associate '], ['Hollywood', 'Tonys', 'Shelf'], ['Compton', 'Sally', 'Shelves']],'B': [['SAC', 'Sallys', 'Associate '], ['Townsland', 'Tonys', 'Shelf'], ['Compton', 'Tiffanys', 'Shelves']]}
b_dict = {'Site':"", 'Store':"", 'Station':""}
for key in a_dict:
b_dict.update(a_dict)
#print(b_dict[key[0]])
#print(value[0])
output = [
{'Site':val[0][0], 'Store':val[1][1], 'Station':val[2]}
for vals in a_dict.values()
for val in vals
]
for x in output:
if x["Station"] in ("Shelf","Shelves"):
x["Store"] += "-B"
else:
x["Store"] += "-A"
print(output)
You said what you needed to do in the last line of your question.

Sorting a list using both length and alphabetically [duplicate]

This question already has answers here:
Length-wise-sorted list but, same length in alphabetical-order in a step
(2 answers)
Closed 5 years ago.
I have a list of all combinations of word HACK like this:
lista = ['H', 'A', 'C', 'K', 'HA', 'HC', 'HK', 'AC', 'AK', 'CK']
I tried sorting the above using :
lista.sort(lambda x,y:cmp(len(x),len(y)))
gives me the same result.
How can I sort with both the length and alphabetically.
Expected Output:
['A', 'C', 'H', 'K', 'AC', 'AH', 'AK', 'CH', 'CK', 'HK']
Update:
from itertools import combinations
inp = "HACK 2".split(" ")
lista = []
for i in range(1,int(inp[1])+1):
for item in list(combinations(inp[0],i)):
lista.append("".join(item))
lista = sorted(lista, key=lambda x: (len(x), x))
print lista
#Output
['A', 'C', 'H', 'K', 'AC', 'AK', 'CK', 'HA', 'HC', 'HK']
#Expected Output
['A', 'C', 'H', 'K', 'AC', 'AH', 'AK', 'CH', 'CK', 'HK']
Also is there anything wrong with how I am iterating the combinations ?
list.sort, sorted accept an optional keyword argument key. Return value of the key function is used to compare elements instead of the elements themselves.
For your case, you can use a key function that returns a tuple of (length, string itself):
>>> lista = ['H', 'A', 'C', 'K', 'HA', 'HC', 'HK', 'AC', 'AK', 'CK']
>>> sorted(lista, key=lambda x: (len(x), x))
['A', 'C', 'H', 'K', 'AC', 'AK', 'CK', 'HA', 'HC', 'HK']
You want to sort not just the lista list, but also all the strings in it. So
>>> lista = ['H', 'A', 'C', 'K', 'HA', 'HC', 'HK', 'AC', 'AK', 'CK']
>>> for i, string in enumerate(lista):
... lista[i] = ''.join(sorted(list(string)))
...
>>> lista
['H', 'A', 'C', 'K', 'AH', 'CH', 'HK', 'AC', 'AK', 'CK']
>>> lista.sort(key=lambda s: (len(s), s))
>>> lista
['A', 'C', 'H', 'K', 'AC', 'AH', 'AK', 'CH', 'CK', 'HK']

Categories

Resources