简体   繁体   English

列表到字典转换,每个键有多个值?

[英]list to dictionary conversion with multiple values per key?

I have a Python list which holds pairs of key/value:我有一个包含键/值对的 Python 列表:

l = [[1, 'A'], [1, 'B'], [2, 'C']]

I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple:我想将列表转换为字典,其中每个键的多个值将聚合成一个元组:

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

The iterative solution is trivial:迭代解决方案很简单:

l = [[1, 'A'], [1, 'B'], [2, 'C']]
d = {}
for pair in l:
    if pair[0] in d:
        d[pair[0]] = d[pair[0]] + tuple(pair[1])
    else:
        d[pair[0]] = tuple(pair[1])

print(d)

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

Is there a more elegant, Pythonic solution for this task?这个任务有更优雅的 Pythonic 解决方案吗?

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',)} d现在包含{1: ('A', 'B'), 2: ('C',)}

d1 is a temporary defaultdict with lists as values, which will be converted to tuples in the last line. d1是一个以列表为值的临时 defaultdict,它会在最后一行转换为元组。 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:使用普通字典通常比defaultdict更可取,特别是如果您只构建一次,然后在稍后的代码中继续读取它:

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.一个普通的字典让你在你想要创建一个键值对时显式地声明,而defaultdict总是隐式地创建它们,在任何类型的访问中。

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):在 Python3 中,这变为(使导出显式):

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.请注意,reduce 已转移到 functools,并且 lambda 不再接受元组。 This version still works in 2.6 and 2.7.此版本在 2.6 和 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)

My data was in a Pandas.DataFrame我的数据在 Pandas.DataFrame 中

myDict = dict()

for idin set(data['id'].values):
    temp = data[data['id'] == id]
    myDict[id] = temp['IP_addr'].to_list()
    
myDict

Gave me a Dict of the keys, ID, mappings to >= 1 IP_addr .给了我一个键、ID、映射到 >= 1 IP_addr的字典。 The first IP_addr is Guaranteed.第一个 IP_addr 是有保证的。 My code should work even if temp['IP_addr'].to_list() == []即使temp['IP_addr'].to_list() == []我的代码也应该工作

{'fooboo_NaN': ['1.1.1.1', '8.8.8.8']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM