Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list to dictionary conversion with multiple values per key?

People also ask

How do you create a dictionary with multiple values per key?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.

How do you create a dictionary from a list of keys and values?

Using zip() with dict() function The simplest and most elegant way to build a dictionary from a list of keys and values is to use the zip() function with a dictionary constructor.

Can a dictionary value have multiple keys?

In this example, if you want to get multiple keys-values then you need to associate an object with each key as a value. In the given dict the keys are strings and with every single key, we assign a list of numbers as a value.

Can you convert a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


from collections import defaultdict

d1 = defaultdict(list)

for k, v in l:
    d1[k].append(v)

d = dict((k, tuple(v)) for k, v in d1.items())

d contains now {1: ('A', 'B'), 2: ('C',)}

d1 is a temporary defaultdict with lists as values, which will be converted to tuples in the last line. This way you are appending to lists and not recreating tuples in the main loop.


Using lists instead of tuples as dict values:

l = [[1, 'A'], [1, 'B'], [2, 'C']]
d = {}
for key, val in l:
    d.setdefault(key, []).append(val)

print(d)

Using a plain dictionary is often preferable over a defaultdict, in particular if you build it just once and then continue to read from it later in your code:

First, the plain dictionary is faster to build and access.

Second, and more importantly, the later read operations will error out if you try to access a key that doesn't exist, instead of silently creating that key. A plain dictionary lets you explicitly state when you want to create a key-value pair, while the defaultdict always implicitly creates them, on any kind of access.


This method is relatively efficient and quite compact:

reduce(lambda x, (k,v): x[k].append(v) or x, l, defaultdict(list))

In Python3 this becomes (making exports explicit):

dict(functools.reduce(lambda x, d: x[d[0]].append(d[1]) or x, l, collections.defaultdict(list)))

Note that reduce has moved to functools and that lambdas no longer accept tuples. This version still works in 2.6 and 2.7.


Are the keys already sorted in the input list? If that's the case, you have a functional solution:

import itertools

lst = [(1, 'A'), (1, 'B'), (2, 'C')]
dct = dict((key, tuple(v for (k, v) in pairs)) 
           for (key, pairs) in itertools.groupby(lst, lambda pair: pair[0]))
print dct
# {1: ('A', 'B'), 2: ('C',)}

I had a list of values created as follows:

performance_data = driver.execute_script('return window.performance.getEntries()')  

Then I had to store the data (name and duration) in a dictionary with multiple values:

dictionary = {}
    for performance_data in range(3):
        driver.get(self.base_url)
        performance_data = driver.execute_script('return window.performance.getEntries()')
        for result in performance_data:
            key=result['name']
            val=result['duration']
            dictionary.setdefault(key, []).append(val)
        print(dictionary)