简体   繁体   中英

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:

[('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. If you instead want to iterate over its key/value pairs, you have to use the dict.items view.

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 .

l[:0] = d.items()

also works

Use items() of dictionary to get key, value and prepend them to list:

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.

You can also have a look at below.

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

For an answer like [('All', 'All'), ('1', '1')] , do:

myList = [('1', '1')]
myList = [('All', 'All')] + myList

For more, reference this .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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