Posts: 4
Threads: 2
Joined: Nov 2018
i have dictionary type, below is output when i read dataframe using json.loads (spark)
{'name':'ename','data':'str','len':'2','add':'bgl','out':'y','zip':'3567','add/blr':'Y'}
but i need output like below.
{'ename':{'data':'str','len':'2','add':'bgl','out':'y','zip':'3567','add/blr':'Y'}
the first element which is name not printed instead value of the name as( ename) should print as fieldkey and i have 20 rows in my file. for each row should print like this .. every row has different value for the name (key)
kindly suggest how can i achieve this through dictionary .
Posts: 48
Threads: 0
Joined: Nov 2017
Nov-23-2018, 02:22 PM
(This post was last modified: Nov-23-2018, 02:23 PM by ODIS.)
Hello amar,
you can do it like this:
lines = [
{'name':'ename','data':'str','len':'2','add':'bgl','out':'y','zip':'3567','add/blr':'Y'},
{'name':'another_name','data':'str','len':'2','add':'bgl','out':'y','zip':'3567','add/blr':'Y'}
]
result = {}
for line in lines:
# extract the name from the line
name = line["name"]
# delete the name from the line
del (line["name"])
# make the record in result
result[name] = line
print(result)
Posts: 4
Threads: 2
Joined: Nov 2018
Nov-24-2018, 01:18 PM
(This post was last modified: Nov-24-2018, 01:24 PM by amar.)
(Nov-23-2018, 02:22 PM)ODIS Wrote: Hello amar,
you can do it like this:
lines = [
{'name':'ename','data':'str','len':'2','add':'bgl','out':'y','zip':'3567','add/blr':'Y'},
{'name':'another_name','data':'str','len':'2','add':'bgl','out':'y','zip':'3567','add/blr':'Y'}
]
result = {}
for line in lines:
# extract the name from the line
name = line["name"]
# delete the name from the line
del (line["name"])
# make the record in result
result[name] = line
print(result)
Hi,
DO i need to convert dict to list again like below, coz there are many rows .. coz im reading csv to df and doing json.loads to get dict
lines = [
{'name':'ename','data':'str','len':'2','add':'bgl','out':'y','zip':'3567','add/blr':'Y'},
{'name':'another_name','data':'str','len':'2','add':'bgl','out':'y','zip':'3567','add/blr':'Y'}
]
Posts: 4,220
Threads: 97
Joined: Sep 2016
If you want it that way, you can just create a new dict and append it to the list:
result = []
for line in lines:
name = line['name']
del line['name']
result.append({name: line}]
Posts: 4
Threads: 2
Joined: Nov 2018
getting error "string indices must be integers for the above code
Posts: 48
Threads: 0
Joined: Nov 2017
Can you post your current code including the file lines processing?
|