1

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?

AlxVallejo
  • 3,066
  • 6
  • 50
  • 74

5 Answers5

1

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

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
1

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.

Austin
  • 25,759
  • 4
  • 25
  • 48
0

You can also have a look at below.

>>> myList = [('1', '1')]
>>>
>>> myList[:0] = dict({'All': 'All'}).items()
>>> myList
[('All', 'All'), ('1', '1')]
>>>
hygull
  • 8,464
  • 2
  • 43
  • 52
0

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

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

For more, reference this.

Vinayak Bagaria
  • 162
  • 2
  • 6
0

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')]))

P.S: 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

Shagun Pruthi
  • 1,813
  • 15
  • 19