Python预先准备了一个dict列表

2024-04-16 18:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个清单:

[('1', '1')]

我想在列表前面加一个dict对象:

[('All', 'All'), ('1', '1')]

我在努力:

myList[:0] = dict({'All': 'All'})

但这给了我:

['All', ('1', '1')]

我做错什么了?你知道吗


Tags: 对象列表alldictmylist
3条回答

使用dictionary的items()获取key、value并将它们预先添加到列表中:

lst = [('1', '1')]
lst = list({'All': 'All'}.items()) + lst

print(lst)
# [('All', 'All'), ('1', '1')]

注意{'All': 'All'}本身就是一个字典,因此代码中的dict({'All': 'All'})是不必要的。你知道吗

你也可以看看下面。你知道吗

>>> myList = [('1', '1')]
>>>
>>> myList[:0] = dict({'All': 'All'}).items()
>>> myList
[('All', 'All'), ('1', '1')]
>>>

当您使用dictin作为iterable时,您只需迭代它的键。如果您想迭代它的键/值对,则必须使用dict.items视图。你知道吗

l = [('1', '1')]
d = dict({'All': 'All'})
print([*d.items(), *l])
# [('All', 'All'), ('1', '1')]

*语法是available in Python 3.5 and later。你知道吗

l[:0] = d.items()

同样有效

相关问题 更多 >