简体   繁体   English

具有嵌套列表的元组到字典中

[英]Tuple with nested list into dictionary

Suppose I have this tuple: 假设我有这个元组:

k=('a', ['email1', 'email2']), ('b',['email3'])

When I do this: 当我这样做时:

j=dict(k)

it should return this according to python documentation: 它应该根据python文档返回它:

{'a': ['email1', 'email2'], 'b': ['email3']}

This is easy enough when the tuple is in key, value pairs. 当元组位于键值对中时,这很容易。 But what if instead it was just one tuple? 但是,如果只是一个元组怎么办? (example below): (下面的示例):

   k=('a', ['email1', 'email2'], 'b',['email3'])

I tried to do: 我试着做:

dict((k,))

But it doesn't work if there is more than one element in the tuple. 但是,如果元组中有多个元素,那么它将不起作用。

EDIT 编辑

  1. Is there a way to do this? 有没有办法做到这一点?
  2. Whats the difference between dict((k,)) and dict[k]? dict((k,))dict[k]?什么区别dict[k]? They seem to give the same output. 他们似乎给出相同的输出。

This is effectively the same problem as How do you split a list into evenly sized chunks in Python? 这实际上是与如何在Python中将列表拆分成大小均匀的块一样的问题 except you want to group it to 2. Ie given: 除非您要将其分组为2。即给出:

def chunk(input, size):
    return map(None, *([iter(input)] * size))

You would do: 您可以这样做:

 k=('a', ['email1', 'email2'], 'b',['email3'])
 dict(chunk(k, 2))

Output: 输出:

{'a': ['email1', 'email2'], 'b': ['email3']}

For your additional questions, are you using python3? 对于其他问题,您是否正在使用python3? dict[k] may hit __getitem__ , but I'm not familiar with python3. dict[k]可能会命中__getitem__ ,但是我对python3不熟悉。 dict((k,)) is hitting the constructor. dict((k,))正在击中构造函数。 In python2.7 they are definitely not equivalent: 在python2.7中,它们绝对不是等效的:

>>> dict((k,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 4; 2 is required
>>> dict[k]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object has no attribute '__getitem__'

You cannot have lists as dictionary keys. 您不能将列表用作字典键。 Dictionary keys can be immutable types, see https://docs.python.org/2/tutorial/datastructures.html#dictionaries 字典键可以是immutable类型,请参见https://docs.python.org/2/tutorial/datastructures.html#dictionaries

By having a tuple with lists as some of the keys as your example shows, it will fail. 如示例所示,通过使用具有列表作为某些键的元组,它将失败。

Also, your tuple example only works when the tuple has two elements, so one can become the key and the other the value. 同样,您的元组示例仅在元组具有两个元素时才有效,因此一个可以成为键,而另一个可以作为值。 I used this example: 我用这个例子:

k=('a', ['email1', 'email2']), ('b',['email3']), ('c',['email4'], 'a')

and because the last tuple has 3 items, it will fail. 并且由于最后一个元组有3个项目,因此它将失败。 Your second example was one tuple of more than 2 elements, so it cannot be converted. 您的第二个示例是一个包含两个以上元素的元组,因此无法将其转换。

I feel you are trying to extend the dict function past what it is meant to do, if you want to custom build dictionaries, look up the dict function, look up dictionary comprehensions, or use for loops to add in elements. 如果您要自定义构建字典,查找dict函数,查找字典理解或使用循环添加元素,我觉得您正在尝试将dict函数扩展到其dict功能之外。

http://legacy.python.org/dev/peps/pep-0274/ <-- dictionary comprehensions http://legacy.python.org/dev/peps/pep-0274/ <- dictionary comprehensions

It's not too clear what you are trying to do, aside from easy tuple-to-dict conversions. 除了简单的元组到字典的转换之外,您还不清楚要做什么。

You can do as follows: 您可以执行以下操作:

k=('a', ['email1', 'email2'], 'b',['email3'])
l = [(k[i], k[i+1]) for i in range(0, len(k), 2)]
l = dict(l)

print l

Output: 输出:

{'a': ['email1', 'email2'], 'b': ['email3']}

You can init a dict with a list of pairs(length 2 tuples), that's why it works in this case: 您可以使用成对的list (长度为2个元组)来初始化dict ,这就是在这种情况下它起作用的原因:

k=('a', ['email1', 'email2']), ('b',['email3'])
dict(k)     # key: a, b
            # value: ['email1', 'email2'], ['email3']

The constructor of dict would take the first element in each tuple as key, and the second one as value. dict的构造函数将每个tuple的第一个元素作为键,将第二个元素作为值。

In this second case, what you pass is one tuple with four elements, there is no heuristic for dict to distinguish 'key' and 'value'. 在第二种情况下,您传递的是一个包含四个元素的tupledict没有启发式来区分“键”和“值”。 Therefore, you need to follow @Kit Sunde's answer to split your tuples. 因此,您需要遵循@Kit Sunde的回答来拆分元组。

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

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