Unpack a list of dictionaries and access keys and valueswith one-liner for loop

Viewed 470

If I have the following list:

list_numbers = [{1:'one'},{2:'two'},{3:'three'}]

In order to access every item of the list I need to iterate it and then to access the key and value call.items() like:

for numbers in list_numbers:
     for int_rep, str_rep in numbers.items():
         print(f"{int_rep} is written as {str_rep}")

Ideally I would like to iterate just once and I imagine that the first for iteration already knows there will be a dict inside, something like flattening the list on the for loop? Note this code doesn't work!:

for int_rep,str_rep in *list_numbers:
    print(f"{int_rep} is written as {str_rep}")

5 Answers

You can use ChainMap

from collections import ChainMap

list_numbers = [{1: 'one'}, {2: 'two'}, {3: 'three'}]

for int_rep, str_rep in ChainMap(*list_numbers).items():
    print(f"{int_rep} is written as {str_rep}")

You can use a list comprehension like so:

>>> [f'{i} is written as {j}' for numbers in list_numbers for i,j in numbers.items()]
['1 is written as one', '2 is written as two', '3 is written as three']

The syntax is sorta kinda unintuitive. The right way to view it is to take your initial multi-line nested loop and put the last line to the top:

for numbers in list_numbers:
    for int_rep, str_rep in numbers.items():
        # work with int_rep, str_rep <-- this part has to go to the top

so you'd have:

[(int_rep, str_rep) for numbers in list_numbers for int_rep, str_rep in numbers.items()]

From there, you can do whatever you need with (int_rep, str_rep).

well there's always list-comprehension...

[print(f"{int_rep} is written as {str_rep}")  for d in list_numbers for int_rep, str_rep in d.items()]
list_numbers = [{1:'one'},{2:'two'},{3:'three'}]

for int_rep,str_rep in [(int_rep,str_rep) for x in list_numbers for (int_rep,str_rep) in x.items()]:
    print(f"{int_rep} is written as {str_rep}")

try this one:

for number in list_numbers:
   (int_rep,str_rep), = number.items()
   print(f"{int_rep} is written as {str_rep}")
Related