tt600
tt600

Reputation: 25

how can i combine all the values of an item in other list using dictionaries in python?

i have two lists and need to combine the into one dictionary that the key are the letters and the values are the value in the other list. for example:

map_keys_to_values_list(["a", "b", "a"], [15, 3, 6])

wll give me :

{'a': [15, 6], 'b': [3]}

i tried:

def keys_to_values_list(k_lst, v_lst):
    lst = []
    for i in range(len(k_lst)):
        v=[]
        #v.append(v_lst[i])
        t = (k_lst[i],v)
        lst.append(t)
    my_dict = dict(lst)
    for k in my_dict.keys():
        val = my_dict.get(k)
        for m in range(len(k_lst)):
            val.append(v_lst[m])


    return my_dict

but i get all the values in my value list

Upvotes: 2

Views: 63

Answers (3)

Vasilis G.
Vasilis G.

Reputation: 7846

Try this one too:

def mapKeysToValues(keyList, valueList):
    return {k : [value for index, value in enumerate(valueList) if keyList[index]==k] for k in keyList}

keyList = ["a", "b", "a"]
valueList = [15, 3, 6]

print(mapKeysToValues(keyList, valueList))

Output:

{'a': [15, 6], 'b': [3]}

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78546

You can use collections.defaultdict passing the default factory as list to collect all the values belonging to the same character:

from collections import defaultdict

def map_keys_to_values_list(keys, values):
    d = defaultdict(list)
    for k, v in zip(keys, values):
        d[k].append(v)
    d.default_factory = None
    return d

After building the dict, you can set the default_factory of the dict to None so that further key access does not produce a new list for missing keys, but instead will raise the more appropriate KeyError:

>>> d = map_keys_to_values_list(["a", "b", "a"], [15, 3, 6])
>>> d
defaultdict(None, {'a': [15, 6], 'b': [3]})
>>> d['c']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'

Upvotes: 4

Sam
Sam

Reputation: 1552

def keys_to_values_list(keys, values):
    d = dict()
    for i in range(len(keys)):
        if keys[i] in d:
            d[keys[i]].append(values[i])
        else:
            d[keys[i]] = [values[i]]
    return d

Upvotes: 2

Related Questions