'Multiply two lists with dicts python
list1 = [{'the': '0.181'}, {'to': '0.115'}, {'a': '0.093'}, {'of': '0.084'}, {'and': '0.078'}]
list2 = [{'the': '1.010'}, {'to': '1.010'}, {'a': '1.000'}, {'of': '1.102'}, {'and': '1.228'}]
As result I am trying to get a new list like this:
[{'the': 'list1 *list2'}, {'to': 'list1*list2'},
{'a': 'list1*list2'}, {'of': 'list1*list2'}, {'and': 'list1*list2'}]
So my question is, how can I multiply these two lists?
Solution 1:[1]
As the list are already sorted in the same order I'd suggest to zip them and apply the multiplication you want
list1 = [{'the': '0.181'}, {'to': '0.115'}, {'a': '0.093'}, {'of': '0.084'}, {'and': '0.078'}]
list2 = [{'the': '1.010'}, {'to': '1.010'}, {'a': '1.000'}, {'of': '1.102'}, {'and': '1.228'}]
result = []
for pair1, pair2 in zip(list1, list2):
k1, v1 = list(pair1.items())[0]
k2, v2 = list(pair2.items())[0]
if k1 != k2:
raise Exception(f"Malformed data ({k1},{v1}).({k2},{v2})")
result.append({k1: float(v1) * float(v2)})
print(result)
# [{'the': 0.18281}, {'to': 0.11615}, {'a': 0.093}, {'of': 0.09256800000000001}, {'and': 0.095784}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | azro |
