-1

If I have the following dictionary...

location_ids: = 
{
'2c50b449-416e-456a-bde6-c469698c5f7': ['422fe2d0-b10f-446d-ac3c-f75e5a3ff138'], 
'61df50b6-3b50-4f22-a175-404089b2ec4f': ['7112fa59-63b1-4057-8822-fe11168c328f']
}

... and what I want to do is get a list of the values from the lists in one list.

At the mo, I can do something like:

locations = [location_ids[i] for i in location_ids]

which returns a list of lists:

[
   ['422fe2d0-b10f-446d-ac3c-f75e5a3ff138'], 
   ['7112fa59-63b1-4057-8822-fe11168c328f']
]

But, how can I change my code to just give me a list of the values like this:

['422fe2d0-b10f-446d-ac3c-f75e5a3ff138', '7112fa59-63b1-4057-8822-fe11168c328f']

I'm hoping as well, if I have more than one id in a values list, like this:

locations_id = {
'2c50b449-416e-456a-bde6-c469698c5f7': ['422fe2d0-b10f-446d-ac3c-f75e5a3ff138','d45ec64a-b41a-41d5-bd47-eed27c6dfd82'], 
'61df50b6-3b50-4f22-a175-404089b2ec4f': ['7112fa59-63b1-4057-8822-fe11168c328f']
}

how can I expand my code to give me:

[
'422fe2d0-b10f-446d-ac3c-f75e5a3ff138',
'd45ec64a-b41a-41d5-bd47-eed27c6dfd82', 
'7112fa59-63b1-4057-8822-fe11168c328f'
]
Mark R
  • 137
  • 1
  • 8
  • Does this answer your question? [How to make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) – jonrsharpe Feb 14 '22 at 15:51
  • Thanks @jonrsharpe. This does help. It seems one way is to get my list of list values as suggested with locations = [location_ids[i][0:] for i in location_ids] and then do a second step with locations_flat = [item for sublist in locations for item in sublist]. Just wondering if there a way to do this in one elegant line of code. – Mark R Feb 14 '22 at 16:16

1 Answers1

0
locations = [location_ids[i][0] for i in location_ids]

You can select the first element of each lists :)

0xDEADBEEF
  • 66
  • 7
  • Thanks. This works nicely. What if I have more than one id in my values list? so locations_id = {'2c50b449-416e-456a-bde6-c469698c5f7': ['422fe2d0-b10f-446d-ac3c-f75e5a3ff138','d45ec64a-b41a-41d5-bd47-eed27c6dfd82'], '61df50b6-3b50-4f22-a175-404089b2ec4f': ['7112fa59-63b1-4057-8822-fe11168c328f']} – Mark R Feb 14 '22 at 15:58
  • You can write : locations = sum(list(locations_id.values()), []) – 0xDEADBEEF Feb 14 '22 at 16:10
  • @0xDEADBEEF summing over lists is quite inefficient, as it creates multiple new lists in the process (this is noted in the top answer on the proposed duplicate: https://stackoverflow.com/a/952952/3001761). – jonrsharpe Feb 14 '22 at 16:12
  • oh, i didn't know that, thanks @jonrsharpe – 0xDEADBEEF Feb 14 '22 at 16:13