4

I have an array of dictionaries. Each dictionary has an "id" as its key and a corresponding list attached to it.

I want to iterate over the list of dictionaries and access the first liste item from each dictionary's value.

As an idea , the data structure is as follows:

[ {"abc": [1,2,3]}, {"def":[4,5,6]} ]

I'd want to iterate through and get [1,4]

Anthony Chung
  • 1,467
  • 2
  • 22
  • 44
  • See the duplicate; apply this to each dictionary and extract the first element of the resulting lists: `[next(d.itervalues())[0] for d in inputlist]` – Martijn Pieters May 08 '16 at 22:18

1 Answers1

2

You want to get the value of each dictionary, using dict.values(), which returns a list of values. Because you know that the dictionary only has one value, the first value is the list you want.

So, you can do this:

first_items = []
for d in my_dicts:
    first_items.append(d.values()[0][0])

You can shorten this into a list comprehension as well.

first_items = [d.values()[0][0] for d in my_dicts]
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94