Appending list of dicts with dicts from list (circular?) - python

I'm trying to loop through a list of dictionaries and search for a specific key. If the value of that key matches a specific value, another list of dictionaries is provided. I would like to append the original list of dictionaries with the new dictionaries.
def test():
info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}]
for item in info:
if "1" in item['a']:
info2 = [{'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]
for dict in info2:
info.append(dict)
I was hoping my above attempt would result in the original info list being as follows:
info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}, {'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]
however I just end up with TypeErrors:
TypeError: string indices must be integers.
Thanks in advance for any assistance

Some issues in your code
You are trying to modify the info list you are iterating on, instead you should iterate on the copy of info via for item in info[:]:
You can change item['a'] to item.get('a') to make sure getting item doesn't thwo an exception if the key is not present, and you can change in to equality
You can add the dictionaries from info2 list to info list by extend the list using list.extend
Then your updated code will be
def test():
info = [{'a': '1', 'b': '2'}, {'a': '3', 'b': '4'}]
#Iterate on copy of info
for item in info[:]:
#If value of a equals 1
if item.get('a') == '1':
#Extend the original list
info2 = [{'c': '1', 'd': '2'}, {'c': '3', 'd': '4'}]
info.extend(info2)
return info
print(test())
And the output will be
[
{'a': '1', 'b': '2'},
{'a': '3', 'b': '4'},
{'c': '1', 'd': '2'},
{'c': '3', 'd': '4'}
]

Related

How to find out the keys of a dictionary with maximum number of common values?

Suppose, there is a dictionary like
my_dict = {'A': {'5', '7', '9', '3'},
'B': {'4', '8','3'},
'C': {'5', '3', '2', '9'},
'D': {'1','6', '8','3'},
'E': {'4','3','5'}}
Now the output should be like {A,C} because they have most number of common values.
dct = {'A': {'5', '7', '9', '3'}, 'B': {'4', '8','3'}, 'C': {'5', '3', '2', '9'}, 'D': {'1','6', '8','3'}, 'E': {'4','3','5'}}
ans = [None, None]
mx = 0
for i in dct:
for j in dct:
if i != j and len(dct[i].intersection(dct[j])) > mx:
ans = [i, j]
mx = len(dct[i].intersection(dct[j]))
As there are sets contained, to find number of common elements, we have intersection method.
>>> ans
['A', 'C']
Although, its worth noting that this code would always produce a pair. If you want more number of elements, the number of loops is going to increase accordingly.

How to merge 3 dict lists in python3 by their order [duplicate]

This question already has answers here:
Combining lists of dictionaries based on list index
(2 answers)
Closed 3 years ago.
I having an issue of finding a way to merge these three lists into one in Python3.
list1 = [{'a': '1'}, {'a': '2'}, {'a': '3'}]
list2 = [{'b': '4'}, {'b': '5'}, {'b': '6'}]
list3 = [{'c': '7'}, {'c': '8'}, {'c': '9'}]
What I would like to do is getting a new list such as:
list4 = [{'a': '1', 'b': '4', 'c': '7'}, {'a': '2', 'b': '5', 'c': '8'}, {'a': '3', 'b': '6', 'c': '9'}]
Is there any Pythonic way to do this operation?
Use zip in a combined list- and dict comprehension:
>>> list1 = [{'a': '1'}, {'a': '2'}, {'a': '3'}]
>>> list2 = [{'b': '4'}, {'b': '5'}, {'b': '6'}]
>>> list3 = [{'c': '7'}, {'c': '8'}, {'c': '9'}]
>>> [{k: d[k] for d in ds for k in d} for ds in zip(list1, list2, list3)]
[{'a': '1', 'b': '4', 'c': '7'},
{'a': '2', 'b': '5', 'c': '8'},
{'a': '3', 'b': '6', 'c': '9'}]
Also works if the dicts contain more than one value. If the dicts in one "column" contain the same keys, the values in the later lists will overwrite the former.

Making a dictionary where key is a list [duplicate]

This question already has answers here:
List of dicts to/from dict of lists
(14 answers)
Closed 4 years ago.
so given a list of dictionaries:
my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'},
{'a': '1', 'b': '8', 'c': '1', 'd': '2'},
{'a': '7', 'b': '4', 'c': '1', 'd': '5'}]
and a list of keys in the dictionary for example [ 'a', 'b']
I am trying to make a list of dictionaries for both 'a' and 'b' for their respective values i.e the final product will resemble
new_dict = ['a':['4', '1', '7'], 'b':['5', '8', '4']]
any help will be appreciated
Using collections
Demo:
import collections
d = collections.defaultdict(list)
my_dict= [{'a': '4', 'b': '5', 'c': '1', 'd': '3'}, {'a': '1', 'b': '8', 'c': '1', 'd': '2'}, {'a': '7', 'b': '4', 'c': '1', 'd': '5'}]
for i in my_dict:
for k,v in i.items():
d[k].append(v)
print( d )
Output:
defaultdict(<type 'list'>, {'a': ['4', '1', '7'], 'c': ['1', '1', '1'], 'b': ['5', '8', '4'], 'd': ['3', '2', '5']})

append values to a dict in python

I have a list of dictionaries -
list1 = [{'id' : '1', 'b' : '2', 'c' : '3'}, {'id' : '4', 'b' : '5', 'c' : '6'}, {'id' : '7', 'b' : '8', 'c' : ''}]
Based on the value of c being null or not, I am making a call which returns -
list2 - {'d' : '30', 'id' : 1}, {'d': '25', 'id' : '4'}
Now I want to modify list1, so that the final list has the values of d for the ids which have c. For example -
list1 = [{'id' : '1', 'b' : '2', 'c' : '3', 'd' : '30'}, {'id' : '4', 'b' : '5', 'c' : '6', 'd' : '25'}, {'id' : '7', 'b' : '8', 'c' : ''}]
My approach -
for l in list2:
current_list = {}
for l2 in list1:
if l2['id'] == l['id']:
current_list = l2
break
if current_list:
current_list['d'] = l['d']
Here the actual dict is not getting modified. How can I modify the actual list? Also, is there a neater way to do this?
I'm not certain I understand what you are trying to accomplish. Your written description of your goal does not agree with you code. Based on the code, I'm guessing that you want to match up the data based on the id values.
# You've got some dicts.
dicts = [
{'id': '1', 'b': '2', 'c': '3'},
{'id': '4', 'b': '5', 'c': '6'},
{'id': '7', 'b': '8', 'c': ''},
]
# You've got some other dicts having the same IDs.
d_dicts = [
{'d': '30', 'id': '1'},
{'d': '25', 'id': '4'},
]
# Reorganize that data into a dict, keyed by ID.
dlookup = {d['id'] : d['d'] for d in d_dicts}
# Now add that lookup data to the main list of dicts.
for d in dicts:
i = d['id']
if i in dlookup:
d['d'] = dlookup[i]
Assuming mr FMc are correct, there is in python 3.5 a valid approach to merge dicts. Which in this case would led us to:
dicts = [
{'id': '1', 'b': '2', 'c': '3'},
{'id': '4', 'b': '5', 'c': '6'},
{'id': '7', 'b': '8', 'c': ''},
]
d_dicts = [
{'d': '30', 'id': '1'},
{'d': '25', 'id': '4'},
]
dicts = [{**d, **dict(*filter(lambda x: x["id"] == d["id"], d_dicts))} for d in dicts]
I like these kinda expressions instead of writing it all out, but it has the "benefit" of crashing instead of overwriting stuff when there is more then one dict with the same id. But my solution still overwrites values if there are duplicate keys silently. The inserted value being the value from whatever's second in the dict merge.

Calculate values between two dicts in Python

I have two dict in python one of quantities and the other of prices the both have the same keys
What is the best, and quicks way to calculate Quantity * price for each element in the dict
Example
prices = {'a': '40', 'b': '40', 'c': '35'}
data ={'a': '1', 'b': '2', 'c': '4'}
I want to get a total sum (int) of 260
You can use sum over a generator expression like this:
sum(float(v)*float(prices[k]) for k,v in data.iteritems())
>>> prices = {'a': '40', 'b': '40', 'c': '35'}
>>> data ={'a': '1', 'b': '2', 'c': '4'}
>>> sum(int(prices[x])*int(data[x]) for x in data)
260

Categories

Resources