Home > Software engineering >  Python3: make csv from array of dictonaries choose the keys from another list
Python3: make csv from array of dictonaries choose the keys from another list

Time:12-14

we have one list which will have the key that value need to select

the list is

ll= ["name", "school", "age"]

the actual data is

dd= [{'p_name': 'school', 'p_value': 'abcd'}, {'p_name': 'escal group', 'p_value': ['PIppT SS PRaaOD']}, {'p_name': 'laptop', 'p_value': ['Dell']}, {'p_name': 'address', 'p_value': ['richmond street']}, {'p_name': 'name', 'p_value': ['subodh']}, {'p_name': 'age', 'p_value': ['33']}, {'p_name': 'friends name', 'p_value': 'leena'}]

Expected data

to_csv=[{'p_name': 'school', 'p_value': 'abcd'}, {'p_name': 'name', 'p_value': ['subodh']}, {'p_name': 'age', 'p_value': ['33']}]

And we want to convert it to csv

"school,name,age"
"abcd,subodh,33"

I have tried the below way but not working

for d in dict_data:
          for c in ll:
              hh={}
              if(d['p_name'] == c):
                  hh[d['p_name']] = d['p_value']
     print("The actual data\n\n\n\n\n\n")
     print(hh)          

CodePudding user response:

Iterate over the list of dictionaries dd and check if the value corresponding to key-p_name is in ll.

to_csv = [d for d in dd if d['p_name'] in ll]        

lst = [[],[]]
for d in to_csv:
    lst[0].append(d['p_name'])
    lst[1].append(d['p_value'] if not isinstance(d['p_value'], list) else d['p_value'][0])

out = '\n'.join((','.join(l1) for l1 in lst))

Output:

'school,name,age\nabcd,subodh,33'

CodePudding user response:

You can use a simple list comprehension for that:

to_csv = [d for d in dd if d["p_name"] in ll]

This will keep all the dictionaries d where d["p_name"] is in ll.

  • Related