简体   繁体   中英

Python dictionary conversion

I have a Python dictionary:

adict = {
    'col1': [
        {'id': 1, 'tag': '#one#two'},
        {'id': 2, 'tag': '#two#'},
        {'id': 1, 'tag': '#one#three#'}
    ]
}

I want the result as follows:

Id tag
1  one,two,three
2  two

Could someone please tell me how to do this?

Try this

import pandas as pd
d={'col1':[{'id':1,'tag':'#one#two'},{'id':2,'tag':'#two#'},{'id':1,'tag':'#one#three#'}]}

df = pd.DataFrame()
for i in d:
    for k in d[i]:
        t = pd.DataFrame.from_dict(k, orient='index').T
        t["tag"] = t["tag"].str.replace("#",",")
        df = pd.concat([df,t])

tf = df.groupby(["id"])["tag"].apply(lambda x : ",".join(set(''.join(list(x)).strip(",").split(","))))

Here is a simple code

import pandas as pd

d = {'col1':[{'id':1,'tag':'#one#two'},{'id':2,'tag':'#two#'},{'id':1,'tag':'#one#three#'}]}


df = pd.DataFrame(d)

df['Id'] = df.col1.apply(lambda x: x['id'])

df['tag'] = df.col1.apply(lambda x: ''.join(list(','.join(x['tag'].split('#')))[1:]))

df.drop(columns = 'col1', inplace = True)
Output:
Id Tag
1  one, two
2  two
1  one, three 

If order of tags is important first remove trailing # and split by # , then per groups remove duplicates and join :

df = pd.DataFrame(d['col1'])
df['tag'] = df['tag'].str.strip('#').str.split('#')
f = lambda x: ','.join(dict.fromkeys([z for y in x for z in y]).keys())
df = df.groupby('id')['tag'].apply(f).reset_index()
print (df)
   id            tag
0   1  one,two,three
1   2            two

If order of tags is not important for remove duplicates use set s:

df = pd.DataFrame(d['col1'])
df['tag'] = df['tag'].str.strip('#').str.split('#')
f = lambda x: ','.join(set([z for y in x for z in y]))
df = df.groupby('id')['tag'].apply(f).reset_index()
print (df)
   id            tag
0   1  three,one,two
1   2            two

dic=[{'col1':[{'id':1,'tag':'#one#two'},{'id':2,'tag':'#two#'},{'id':1,'tag':'#one#three#'}]}]

row=[] for key in dic: data=key['col1'] for rows in data: row.append(rows) df=pd.DataFrame(row) print(df)

o

I tried as below

import pandas as pd
a = {'col1':[{'id':1, 'tag':'#one#two'},{'id':2, 'tag':'#two#'},{'id':1, 'tag':'#one#three#'}]}

df = pd.DataFrame(a)
df[["col1", "col2"]] = pd.DataFrame(df.col1.values.tolist(), index = df.index)
df['col1'] = df.col1.str.replace('#', ',')
df = df.groupby(["col2"])["col1"].apply(lambda x : ",".join(set(''.join(list(x)).strip(",").split(","))))

O/P:
col2
1    one,two,three
2    two

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM