[英]Python Prepend a list of dicts
I have this list: 我有这个清单:
[('1', '1')]
and I want to prepend the list with a dict object to look like: 我想在列表前添加一个dict对象,看起来像:
[('All', 'All'), ('1', '1')]
I'm trying: 我正在努力:
myList[:0] = dict({'All': 'All'})
But that gives me: 但这给了我:
['All', ('1', '1')]
What am I doing wrong? 我究竟做错了什么?
When you use a dict
in as an iterable, you only iterate over its keys. 当您将dict
用作可迭代对象时,您仅在其键上进行迭代。 If you instead want to iterate over its key/value pairs, you have to use the dict.items
view. 相反,如果要遍历其键/值对,则必须使用dict.items
视图。
l = [('1', '1')]
d = dict({'All': 'All'})
print([*d.items(), *l])
# [('All', 'All'), ('1', '1')]
The *
syntax is available in Python 3.5 and later . *
语法在Python 3.5及更高版本中可用 。
l[:0] = d.items()
also works 也可以
Use items()
of dictionary to get key, value and prepend them to list: 使用字典的items()
获取键,值并将它们放在列表的前面:
lst = [('1', '1')]
lst = list({'All': 'All'}.items()) + lst
print(lst)
# [('All', 'All'), ('1', '1')]
Note : {'All': 'All'}
is a dictionary itself, so dict({'All': 'All'})
in your code is unnecessary. 注意 : {'All': 'All'}
本身就是字典,因此代码中的dict({'All': 'All'})
是不必要的。
You can also have a look at below. 您也可以在下面查看。
>>> myList = [('1', '1')]
>>>
>>> myList[:0] = dict({'All': 'All'}).items()
>>> myList
[('All', 'All'), ('1', '1')]
>>>
You can refer the function below for appending any dict as list items to already present list. 您可以参考以下函数,将任何字典作为列表项追加到已经存在的列表中。 You just have to send a new dict which you want to append with the old list already present with you. 您只需要发送一个新的字典,然后将其附加到已经存在的旧列表中即可。
def append_dict_to_list(new_dict,old_list):
list_to_append = list(new_dict.items())
new_list = list_to_append + old_list
return new_list
print (append_dict_to_list({'All':'All'},[('1', '1')]))
PS: If you want the new dict to be appended after the existing list, just change the sequence in code as new_list = old_list + list_to_append PS:如果要在现有列表后追加新字典,只需将代码中的顺序更改为new_list = old_list + list_to_append
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.