list - python 2.7:iterate dictionary and map values to a file -


i have list of dictionaries build .xml file:

list_1=[{'lat': '00.6849879', 'phone': '+3002201600', 'amenity': 'restaurant', 'lon': '00.2855850', 'name': 'telegraf'},{'lat': '00.6850230', 'addr:housenumber': '6', 'lon': '00.2844493', 'addr:city': 'xxx', 'addr:street': 'yyy.'},{'lat': '00.6860304', 'crossing': 'traffic_signals', 'lon': '00.2861978', 'highway': 'crossing'}] 

my aim build text file values (not keys) in such order: lat,lon,'addr:street','addr:housenumber','addr:city','amenity','crossing' etc...

00.6849879,00.2855850, , , ,restaurant, ,'\n'00.6850230,00.2844493,yyy,6,xxx, , ,'\n'00.6860304,00.2861978, , , , ,traffic_signals,'\n' 

if value not exists there should empty space.


i tried loop loop:

for in list_1:     line= i['lat'],i['lon']      print line 

problem occurs if add value not exist in cases:

for in list_1:     line= i['lat'],i['lon'],i['phone']     print line 

also tried loop , use map() function, results seems not correct:

for in list_1:     line=map(lambda x1,x2:x1+','+x2+'\n',i['lat'],i['lon'])     print line 

also tried:

 in list_1:     k,v in i.items():         if k=='addr:housenumber':         print v 

this time think there might many if/else conditions write.


seems solutions somewhere close. can't figure out solution , optimal way.

i use csv module, in particular dictwriter. fieldnames dictate order in dictionary information written out. writing header optional:

import csv fields = ['lat','lon','addr:street','addr:housenumber','addr:city','amenity','crossing',...] open('<file>', 'w') f:     writer = csv.dictwriter(f, fields)     #writer.writeheader()   # if want header     writer.writerows(list_1) 

if didn't want use csv module can simple iterate on list of fields want in order want them:

fields = ['lat','lon','addr:street','addr:housenumber','addr:city','amenity','crossing',...] row in line_1:     print(','.join(row.get(field, '') field in fields)) 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -