简体   繁体   English

列表理解 - 尝试从键值对数组的数组中创建字典

[英]List comprehension - attempting to create dictionary from array of key-value pair arrays

While trying to create a dict using list comprehension (without overwriting generated list keys)在尝试使用列表理解创建 dict 时(不覆盖生成的列表键)

x = {}
entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
discardable = [x.setdefault(entry[0], []).append(entry[1]) for entry in entries]

Error: name 'x' is not defined

I was expecting x to be populated as:我期待 x 被填充为:

{1: ['1a', '1b'], 2: ['2a', '2b'], 3: ['3a', '3b']}

How to explain this / make this work?如何解释这一点/使这项工作? Is there any other way to achieve this?有没有其他方法可以实现这一目标?

You can try:你可以试试:

from collections import defaultdict
entries = [['1','1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
x = defaultdict(list)
[x[a].append(b) for a,b in entries]
x = dict(x)

Output输出

{'1': ['1a', '1b'], 2: ['2a'], 3: ['3a'], '2': ['2b'], '3': ['3b']}

Some of the keys are str and some are int , so this will produce有些键是str ,有些是int ,所以这将产生

{'1': ['1a', '1b'], 2: ['2a'], 3: ['3a'], '2': ['2b'], '3': ['3b']}

You need to cast entry[0] to int您需要将entry[0]int

x = {}
entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
[x.setdefault(int(entry[0]), []).append(entry[1]) for entry in entries]

print(x) will give print(x)会给

{1: ['1a', '1b'], 2: ['2a', '2b'], 3: ['3a', '3b']}

What you want is to merge the value of (1, '1'), (2, '2'), (3, '3').你想要的是合并 (1, '1'), (2, '2'), (3, '3') 的值。 The code you provided works, but it doesn't handle the type between int and str .您提供的代码有效,但它不处理intstr之间的类型。 All you need to do is cast str into int so the value would be merged.您需要做的就是将str转换为int以便合并该值。

Try this:尝试这个:

x = {}
entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]
discardable = [x.setdefault(int(entry[0]), []).append(entry[1]) for entry in entries]

How to explain this / make this work?如何解释这一点/使这项工作?

A comprehension creates one output for each input, and they're not intended for mutation理解为每个输入创建一个输出,并且它们不用于突变

Is there any other way to achieve this?有没有其他方法可以实现这一目标?

Use a normal procedural loop.使用正常的程序循环。 Or use a multidict but the standard library doesn't provide one.或者使用 multidict 但标准库不提供。

You could perform functional transformations until you get the proper "shape" (using sorted , itertools.groupby and some more mapping) but I don't think that'd be worth it, a bog-standard for loop would be much more readable:直到你得到正确的“形”可以进行功能转换(使用sorteditertools.groupby和一些映射),但我不认为这会是值得的,一个沼泽标准for循环会更可读:

for k, v in entries:
    x.setdefault(int(x), []).append(v)

versus:相对:

x = {
    x: list(v[1] for v in vs)
    for x, vs in itertools.groupby(
        sorted((int(k), v) for k, v in entries),
        lambda it: it[0]
    )
}

the comprehension is less readable and less efficient理解的可读性和效率都较低

You can use a dict comprehension .您可以使用dict comprehension they work much like list comprehensions它们的工作方式很像列表推导式

entries = [[1,'1a'], [2,'2a'], [3,'3a'], ['1', '1b'], ['2', '2b'], ['3', '3b']]

# Build a dictionary from the values in entries
discardable = {key:val for key, val in entries}

print (discardable)
# Result: {1: '1a', 2: '2a', 3: '3a', '1': '1b', '2': '2b', '3': '3b'}

暂无
暂无

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

相关问题 根据来自单独列表的匹配项,使用来自字典列表中的值的键值对创建一个新字典 - Create a new dictionary with the key-value pair from values in a list of dictionaries based on matches from a separate list 如何将新的键值对添加到字典中,其中值是数组的数组 - How to add new key-value pair into dictionary where value is array of arrays 将嵌套列表与字典键进行比较并创建复合键值对 - Comparing nested list with dictionary keys and create compound key-value pair 如何将现有列表转换为 Python 中字典的键值对? - How to turn an existing list into a key-value pair for a dictionary in Python? 从列列表中的元素中获取字典,其中键值对是 pandas 中元素的数量和元素值 - Get the dictionary from elements in the list of a column where key-value pair are number of elements and element value in pandas 从字典的键值对中提取值 - Extract value from key-value pair of dictionary 有没有办法从 python 中的字典中的键值对创建字符串? - Is there a way to create a string out of a key-value pair from a dictionary in python? 如何从基于另一个键值对的列表中的字典中访问值? - How to access values from a dictionary inside a list based on another key-value pair? 从具有相同名称字段的字典列表中删除键值对 - Delete a key-value pair from a list of dictionary having field of same name 在不使用列表、迭代器的情况下从 Python 中的字典中检索第一个键值对 - Retrieve first key-value pair from a dictionary in Python without using list, iter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM