3

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?

Bidhan Bhattarai
  • 1,040
  • 2
  • 12
  • 20
  • What's your *specific indices* and what's your expected output? Can you add a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) to your question? – Mazdak Feb 26 '16 at 08:44

2 Answers2

1

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: []}
Bidhan Bhattarai
  • 1,040
  • 2
  • 12
  • 20
0

Since you just want the first two columns you can simply loop over them. You can use a nested list comprehension to create a flatten list from first two column and use dict.fromkeys to create a dictionary form an iterable by specifying the common value and use collections.OrderedDict() in order to keep the order:

>>> from collections import OrderedDict
>>> my_dict = OrderedDict.fromkeys([i for sub in data for i in sub[:2]],[])
>>> my_dict
OrderedDict([('a', []), ('b', []), ('d', []), ('e', []), ('g', []), ('h', [])])
>>> my_dict['a']
[]
Mazdak
  • 105,000
  • 18
  • 159
  • 188