-2

How do you split a list of dictionaries and assign it to variables a and b to compare it? For example: How can I get results and assign them to a and b like below?

Problem:

results = [
{
"name": "Sarah",
"age": 45
},
{
"name": "Sarah",
"age": 18
}
]

Desired outcome:

a = {
"name": "John",
"age": 45
}

b = {
"name": "John",
"age": 18
}

This is my solution but I dont feel it is the right way to do it:

a = {}
b = {}
i = 0
for result in results:
   if i == 0:
     a = result
   else:
     b = result
   i += 1

Thank you.

  • 1
    why would you do that? It's much better to keep the original container. If you really want to have keys, use a dictionary: `d = dict(zip(['a', 'b'], results))` – mozway Jun 10 '22 at 07:34

1 Answers1

0

If you just have these two values:

a, b = results

Python allows sequence unpacking (search in this doc), which allows you to decompose a sequence object into individual variables.

There are some other, pretty cool things you can do. If you want to get only the first two, or the last two, for example, you can do something like:

a, b, *c = results # get first two, store rest in c
*a, b, c = results # get last two, store rest in a
M Z
  • 4,571
  • 2
  • 13
  • 27