[英]How to split a list of lists into dictionary key/values pairs?
I have the following list
: 我有以下list
:
is_censored = [[True, True], [False, True], [False, False]]
which I want to place into a dictionary
with keys/values equal to is_censored_1 = [True, True]
, is_censored_2=[False, True]
and is_censored_3=[False, False]
. 我想将其放入具有等于is_censored_1 = [True, True]
, is_censored_2=[False, True]
和is_censored_3=[False, False]
键/值的dictionary
。
Can this be achieved pythonically? 可以通过Python实现吗?
So far I have this: 到目前为止,我有这个:
data = dict()
for i, value in enumerate(is_censored):
data['_'.join(['is_censored', str(i + 1)])] = value
which yields the right result: 产生正确的结果:
data = {'is_censored_1': [True, True], 'is_censored_2': [False, True], 'is_censored_3': [False, False]}
but is not that appealing to the eyes. 但这并不吸引眼球。
You can use a dictionary comprehension with enumerate
to format the f-strings : 您可以使用带有enumerate
的字典理解来格式化f字符串 :
{f'is_censored_{i+1}': l for i,l in enumerate(is_censored)}
{'is_censored_1': [True, True],
'is_censored_2': [False, True],
'is_censored_3': [False, False]}
Note: for python versions < 3.6
use string.format()
as in @devesh's answer . 注意:对于版本< 3.6
python,请使用string.format()
如@devesh的answer所示 。 You can check the docs for more details 您可以检查文档以了解更多详细信息
You can use dictionary comprehension for this, where you get both index and item of list is_censored
using enumerate
, then make key-value pairs accordingly! 您可以为此使用字典理解,在此您可以使用enumerate
获得is_censored
索引和列表项,然后相应地创建键值对!
is_censored = [[True, True], [False, True], [False, False]]
res = {'is_censored_{}'.format(idx+1):item for idx, item in enumerate(is_censored)}
print(res)
The output will be 输出将是
{'is_censored_1': [True, True], 'is_censored_2': [False, True], 'is_censored_3': [False, False]}
is_censored = [[True, True], [False, True], [False, False]]
res ={'is_censored_{}'.format(i+1):is_censored[i] for i in range(len(is_censored))}
output 输出
{'is_censored_1': [True, True],
'is_censored_2': [False, True],
'is_censored_3': [False, False]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.