user3001937
user3001937

Reputation: 2113

Python: Using Map/Lambda instead of For-Loop

I am working to convert CSV file to structured Json file.

CSV.File

address,type,floor,door
"1","is","an","example"
"2","is","an","example"
"3","is","an","example"
"4","is","an","example"
"5","is","an","example"
"6","is","an","example"
"7","is","an","example"

First, I read the csv file and list all the column's items to lists.

import pandas as pd

with open('data.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
    df = pd.read_csv(csvfile)
    listAddress= df.address
    listType= df.type
    listFloor= df.floor
    listDoor=df.door

In order to get lists like this one :

listAddress=["1","2","3","4","5","6","7"]

Now, I want to automate the process and make a list of dictionaries

Output= []
tempJson =  {"1": 1,"2": "is"}

for i in range(len(listAddress)):
  tempJson["Address"]= listAddress[i]
  tempJson["Type"]= listType[j]
  Output.(tempJson)

json.dumps(output)

Here is the problem, I'd like to make a list of dictionaries, I can do this in JS using map. But I am not proficient in Python. Can I simplify the this last piece of code using Map

Output: 
[
    {
        "1": 1,
        "2": "is"
    },
    {
        "1": 2,
        "2":"is"
    },
    {
        "1": 3,
        "2": "is"
    },{
        "1": 4,
        "2": "is"
    },
    {
        "1": 5,
        "2":"is"
    },
    {
        "1": 6,
        "2": "is"
    },
    {
        "1": 7,
        "2": "is"
    }
]

Upvotes: 0

Views: 387

Answers (2)

6502
6502

Reputation: 114559

A simple change would be

Output= []
tempJson =  {"1": 1,"2": "is"}

for i in range(len(listAddress)):
  tempJson["Address"]= listAddress[i]
  tempJson["Type"]= listType[i]
  Output.append(tempJson.copy())

something probably considered more pythonic would be:

output = [{"1": 1, "2": "is", "Address": a, "Type": t}
          for a, t in zip(listAddress, listType)]

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251061

You can use a list comprehension here:

>>> from pprint import pprint
>>> import csv
>>> with open('data.csv') as f:
    next(f)  #skip the header
    reader = csv.reader(f, delimiter=',', quotechar='"')
    d = [{'1':int(row[0]), '2': row[1]} for row in reader]
...     
>>> pprint(d)
[{'1': 1, '2': 'is'},
 {'1': 2, '2': 'is'},
 {'1': 3, '2': 'is'},
 {'1': 4, '2': 'is'},
 {'1': 5, '2': 'is'},
 {'1': 6, '2': 'is'},
 {'1': 7, '2': 'is'}]

Upvotes: 1

Related Questions