Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dictionary from nested list using dictionary comprehension

Is there a way to create a dictionary with a nested list but for specific indices?
I have input:

 data = [[int, int, int], [int, int, int], [int, int,int]]

I want to so something along the lines of:

my_dictionary = {}
    for x in data:
       my_dictionary[x[0]] = []
       my_dictionary[x[1]] = []

but without having to iterate through the whole thing.

For example:

data = [[a,b,c], [d,e,f], [g,h,i]] 
# would leave me with:
my_dictionary = {a: [] , b:[], d:[], e:[], g:[], h:[] }

Is there a way to specify this using dictionary comprehension?

like image 207
Daniela Carrasco Avatar asked Jun 02 '26 11:06

Daniela Carrasco


1 Answers

Just do this:

>>> data
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> {d[i]:[] for i in (0,1) for d in data}
{1: [], 2: [], 4: [], 5: [], 7: [], 8: []}
like image 157
Bidhan Bhattarai Avatar answered Jun 04 '26 02:06

Bidhan Bhattarai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!