Sum values in a dict of lists - python

If I have a dictionary such as:
my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}
How do I create a new dictionary with sums of the values for each key?
result = {"A": 6, "B": 7, "C": 103}

Use sum() function:
my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}
result = {}
for k, v in my_dict.items():
result[k] = sum(v)
print(result)
Or just create a dict with a dictionary comprehension:
result = {k: sum(v) for k, v in my_dict.items()}
Output:
{'A': 6, 'B': 7, 'C': 103}

Try This:
def sumDictionaryValues(d):
new_d = {}
for i in d:
new_d[i]= sum(d[i])
return new_d

Just a for loop:
new = {}
for key in dict:
new_d[key]= sum(d[key])
new the dictionary having all the summed values

One liners- for the same, just demonstrating some ways to get the expected result,in python3
my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}
Using my_dict.keys():- That returns a list containing the my_dict's keys, with dictionary comprehension.
res_dict = {key : sum(my_dict[key]) for key in my_dict.keys()}
Note that my_dict.keys() produce a list of keys in the dictionary,
But python dictionary data structure also got an iterator implementation to loop
through keys, (which is faster, but not recommended always) so, this
will also give same result,
res_dict = {key : sum(my_dict[key]) for key in my_dict}
Using my_dict.items():- That returns a list containing a tuple for each key
value pair of dictionary, by unpacking them gives a best single line solution for this,
res_dict = {key : sum(val) for key, val in my_dict.items()}
Using my_dict.values():- That returns a list of all the values in the
dictionary(here the list of each lists),
note:- This one is not intended as a direct solution, just for demonstrating the three python methods used to traverse through a dictionary
res_dict = dict(zip(my_dict.keys(), [sum(val) for val in my_dict.values()]))
The zip function accepts iterators(lists, tuples, strings..), and pairs similar indexed items together and returns a zip object, by using dict it is converted back to a dictionary.

Related

comparing list of dict and list and get corresponding value's key

I have two lists, lst and my_dict. lst is storing IDs and lst_of_dict is a dictionaries with keys and values of ID.
Here I want to extract keys from lst_of_dict and add them into a new list if the corresponding values are matched with the ID of lst.
Here is the examples:
lst = [1, 2, 5]
my_dict = {'44': 2, '801': 1, '7': 5}
given these lists, I want to create a new list like below:
new_lst = [801, 44, 7]
How do you accomplish this? Thank you in advance.
[EDIT]
I'm really sorry but type of lst_of_dict is a dict, I was wrong.
You can iterate over the list of dictionaries and use index to replace the values in a copy of the original list (or just the original list if you don't want to preserve it)
lst = [1, 2, 5]
my_dict = {'44': 2, '801': 1, '7': 5}
new_lst = lst[:]
for k, v in my_dict.items():
new_lst[new_lst.index(v)] = int(k)
print(new_lst) # [801, 44, 7]
Edit:
If there might be a mismatch between the values in the list and the dictionary you can initialize the new list with Nones and filter them afterwards
new_lst = [None] * len(lst)
for k, v in my_dict.items():
if v in lst:
new_lst[lst.index(v)] = int(k)
new_lst = list(filter(lambda x: x, new_lst))
Here is a way you can do it:
lst = [1, 2, 5]
lst_of_dict = [
{'44': 2},
{'801': 1},
{'7': 5}
]
invert = {i:int(k)for v in lst_of_dict for k,i in v.items()}
print([invert.get(x) for x in invert])
#== Output [44, 801, 7]

Combining a nested list without affecting the key and value direction in python

I have a program that stores data in a list. The current and desired output is in the format:
# Current Input
[{'Devices': ['laptops', 'tablets'],
'ParentCategory': ['computers', 'computers']},
{'Devices': ['touch'], 'ParentCategory': ['phones']}]
# Desired Output
[{'Devices': ['laptops', 'tablets','touch'],
'ParentCategory': ['computers', 'computers','phones']}]
Can you give me an idea on how to combine the lists with another python line of code or logic to get the desired output?
You can do something like this:
def convert(a):
d = {}
for x in a:
for key,val in x.items():
if key not in d:
d[key] = []
d[key] += val
return d
Code above is for Python 3.
If you're on Python 2.7, then I believe that you should replace items with iteritems.
Solution using a dict comprehension: build the merged dictionary first by figuring out which keys it should have, then by concatenating all the lists for each key. The set of keys, and each resulting list, are built using itertools.chain.from_iterable.
from itertools import chain
def merge_dicts(*dicts):
return {
k: list(chain.from_iterable( d[k] for d in dicts if k in d ))
for k in set(chain.from_iterable(dicts))
}
Usage:
>>> merge_dicts({'a': [1, 2, 3], 'b': [4, 5]}, {'a': [6, 7], 'c': [8]})
{'a': [1, 2, 3, 6, 7], 'b': [4, 5], 'c': [8]}
>>> ds = [
{'Devices': ['laptops', 'tablets'],
'ParentCategory': ['computers', 'computers']},
{'Devices': ['touch'],
'ParentCategory': ['phones']}
]
>>> merge_dicts(*ds)
{'ParentCategory': ['computers', 'computers', 'phones'],
'Devices': ['laptops', 'tablets', 'touch']}

how to get all the values in a dictionary with the same key? [duplicate]

I want to add multiple values to a specific key in a python dictionary. How can I do that?
a = {}
a["abc"] = 1
a["abc"] = 2
This will replace the value of a["abc"] from 1 to 2.
What I want instead is for a["abc"] to have multiple values (both 1 and 2).
Make the value a list, e.g.
a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
key = "somekey"
a.setdefault(key, [])
a[key].append(1)
Results:
>>> a
{'somekey': [1]}
Next, try:
key = "somekey"
a.setdefault(key, [])
a[key].append(2)
Results:
>>> a
{'somekey': [1, 2]}
The magic of setdefault is that it initializes the value for that key if that key is not defined. Now, noting that setdefault returns the value, you can combine these into a single line:
a.setdefault("somekey", []).append("bob")
Results:
>>> a
{'somekey': [1, 2, 'bob']}
You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
Append list elements
If the dict values need to be extended by another list, extend() method of lists may be useful.
a = {}
a.setdefault('abc', []).append(1) # {'abc': [1]}
a.setdefault('abc', []).extend([2, 3]) # a is now {'abc': [1, 2, 3]}
This can be especially useful in a loop where values need to be appended or extended depending on datatype.
a = {}
some_key = 'abc'
for v in [1, 2, 3, [2, 4]]:
if isinstance(v, list):
a.setdefault(some_key, []).extend(v)
else:
a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 2, 4]}
Append list elements without duplicates
If there's a dictionary such as a = {'abc': [1, 2, 3]} and it needs to be extended by [2, 4] without duplicates, checking for duplicates (via in operator) should do the trick. The magic of get() method is that a default value can be set (in this case empty set ([])) in case a key doesn't exist in a, so that the membership test doesn't error out.
a = {some_key: [1, 2, 3]}
for v in [2, 4]:
if v not in a.get(some_key, []):
a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 4]}

Convert tuple to list in a dictionary

I have a dictionary like this:
a= {1982: [(1,2,3,4)],
1542: [(4,5,6,7),
(4,6,5,7)]}
and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7) to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7]
I have tried
for key, value in a.items():
for i in value:
i = tuple(i)
but it does now work. How can I achieve it?
As far as I understand you want to convert each tuple in a list. You can do this using a dictionary comprehension:
{k: [list(ti) for ti in v] for k, v in a.items()}
will give
{1542: [[4, 5, 6, 7], [4, 6, 5, 7]], 1982: [[1, 2, 3, 4]]}
Is that what you are after?
In-place:
for key, value in a.items():
for i, t in enumerate(value):
value[i]= list(t)
New objects:
{key: [list(t) for t in value] for key, value in a.items()}
You can use "tupleo" library
from tupleo import tupleo.
val = tupleo.tupleToList(a[1542]).
print(val)
[[4,5,6,7], [4,6,5,7]]
tupleo gives you full depth level conversion of tuple to list.
and it have functionality to convert tuple to dict also based on index.

getting list of indices of each value of list in a pythonic way

I have a list data of values, and I want to return a dictionary mapping each value of data to a list of the indices where this value appears.
This can be done using this code:
data = np.array(data)
{val: list(np.where(data==val)[0]) for val in data}
but this runs in O(n^2), and this is too slow for long lists. Can an O(n) solution be coded using a "pythonic" syntax? (it can be done with creating an empty list and updating it in a loop, but I understand this is not recommended in python.)
You can use a defaultdict of lists to achieve this in O(n):
from collections import defaultdict
d = defaultdict(list)
for idx, item in enumerate(data):
d[item].append(idx)
For example, if data contains the string 'abcabccbazzzqa':
d = defaultdict(list)
for idx, item in enumerate('abcabccbazzzqa'):
d[item].append(idx)
>>> d
defaultdict(<type 'list'>, {'a': [0, 3, 8, 13], 'q': [12], 'c': [2, 5, 6], 'b': [1, 4, 7], 'z': [9, 10, 11]})
>>> d['a']
[0, 3, 8, 13]
Try this out :
data = np.array(data)
dic = {}
for i, val in enumerate(data):
if val in dic.keys():
dic[val].append(i)
else:
dic[val]=[]
dic[val].append(i)

Categories