Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list with one key of list of dictionaries

this should be an easy one, but because I am not so familiar with python, I haven't quite figured out how it works. I have the following csv file

name        ; type
apple       ; fruit
pear        ; fruit
cucumber    ; vegetable
cherry      ; fruit
green beans ; vegetable

What I want to achieve is to list all distinct types with its corresponding name such as:

fruit: apple, pear, cherry
vegetable: cucumber, green beans

Reading it in with csv.DictReader I can generate a list of dictionaries of that csv File, saved in the variable alldata.

alldata = 
[
  {'name':'apple', 'type':'fruit'},
  {'name':'pear',  'type':'fruit'},
  ...
]

Now I need a list of all distinct type values from alldata

types = ??? #it should contain [fruit, vegetable]

such that I can iterate over the list and extract my names corresponding to these types:

foreach type in types
  list_of_names = ??? #extract all values of alldata["type"]==type and put them in a new list
  print type + ': ' + list_of_names

Does anybody know, how to achieve this?

like image 385
kiki Avatar asked Oct 22 '25 03:10

kiki


2 Answers

You can use list comprehension to solve this problem :

types = set([data['type'] for data in  alldata])

list_of_name = [data['name'] for data in alldata if data['type']==type]
like image 155
Gabz Avatar answered Oct 23 '25 17:10

Gabz


More general approach is to use itertools.groupby:

from itertools import groupby

food = [
    {'name': 'apple', 'type': 'fruit'}, 
    {'name': 'pear', 'type': 'fruit'}, 
    {'name': 'parrot', 'type': 'vegetable'}]

for group, items in groupby(sorted(food, key=lambda x: x['type']), lambda x: x['type']):
    print group, list(items) # here is group and items' objects in the group

result is:

fruit [{'type': 'fruit', 'name': 'apple'}, {'type': 'fruit', 'name': 'pear'}]
vegetable [{'type': 'vegetable', 'name': 'parrot'}]

UPD: sort dict before groupby. Thanks @mgilson for point!

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.

https://docs.python.org/2/library/itertools.html#itertools.groupby

like image 27
power Avatar answered Oct 23 '25 16:10

power



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!