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
Related
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.
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.
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'}
]
I'm trying to calculate difference between two dictionaries to return a specific value.
I've entered different values which should return different results, but the result remains unchanged.
diets = {"normal" : {'p': '32.50', 'c': '60', 'f': '40.86'},
"oncology" : {'p': '35', 'c': '52.50', 'f': '37.63'},
"cardiology" : {'p': '32.50', 'c': '30', 'f': '26.88'},
"diabetes" : {'p': '20', 'c': '27.50', 'f': '27.95'},
"kidney" : {'p': '15', 'c': '55', 'f': '23.65'}}
amounts = {'p': p, 'c': c, 'f': f}
value = { k : diets[k] for k in set(diets) - set(amounts) }
calculate_error = min(value)
print(calculate_error)
When i input 32, 60 and 40, the returned result should be normal, but oncology is returned instead
You should look at the values you are creating when you do this:
set(diets)
This is just a list of keys.
{'cardiology', 'diabetes', 'kidney', 'normal', 'oncology'}
When you subtract the other list of keys, you just get the original list because no values are in common.
You need to actually step through the items and do the subtraction to get the differences. Then you can find the sum of the diffs and the min of that sum.
One way would be:
diets = {"normal" : {'p': '32.50', 'c': '60', 'f': '40.86'},
"oncology" : {'p': '35', 'c': '52.50', 'f': '37.63'},
"cardiology" : {'p': '32.50', 'c': '30', 'f': '26.88'},
"diabetes" : {'p': '20', 'c': '27.50', 'f': '27.95'},
"kidney" : {'p': '15', 'c': '55', 'f': '23.65'}}
amounts = {'p': 32., 'c': 60., 'f': 40.}
mins = [(diet, sum([abs(amounts[k] - float(d[k])) for k in amounts])) for diet, d in diets.items()]
the_min = min(mins, key = lambda x: x[1])
mins will be:
[('normal', 1.3599999999999994),
('oncology', 12.869999999999997),
('cardiology', 43.620000000000005),
('diabetes', 56.55),
('kidney', 38.35)]
the_min will be:
('normal', 1.3599999999999994)
It looks you totally confused what value would be
>>> diets = {"normal" : {'p':'32.50', 'c':'60', 'f':'40.86'},
... "oncology" : {'p':'35', 'c':'52.50', 'f':'37.63'},
... "cardiology" : {'p':'32.50', 'c':'30', 'f':'26.88'},
... "diabetes" : {'p':'20', 'c':'27.50', 'f':'27.95'},
... "kidney" : {'p':'15', 'c':'55', 'f':'23.65'}}
>>> set(diets)
{'kidney', 'cardiology', 'oncology', 'normal', 'diabetes'}
>>> amounts = {'p':32, 'c':60, 'f':40}
>>> set(amounts)
{'c', 'f', 'p'}
>>> set(diets) - set(amounts)
{'cardiology', 'diabetes', 'kidney', 'oncology', 'normal'}
>>> value = { k : diets[k] for k in set(diets) - set(amounts) }
>>> value
{'cardiology': {'p': '32.50', 'c': '30', 'f': '26.88'},
'diabetes': {'p': '20', 'c': '27.50', 'f': '27.95'},
'kidney': {'p': '15', 'c': '55', 'f': '23.65'},
'oncology': {'p': '35', 'c': '52.50', 'f': '37.63'},
'normal': {'p': '32.50', 'c': '60', 'f': '40.86'}}
>>> min(value)
'cardiology'
that said I would expect that you to get cardiology, i.e. the min from diets.keys()
That said, note that the values in the diets are str, e.g. '32.50', You will need to convert these before any calculations.
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']})