who_am_i
who_am_i

Reputation: 35

Dictionary with multiple key values to dataframe

Dictionary looks like:

{'iphone': [12, 21666], 'a1': [6, 5859], 'J5': [15, 13862]}

Using this dictionary i want to create dataframe that looks like this:

    name   n1   n2
0  iphone  12   21666
1  a1       6   5859
2  J5      15   13862

Upvotes: 1

Views: 4972

Answers (4)

Sumanth
Sumanth

Reputation: 507

Also you can just do this, if your dictionary name is d:

df = pd.DataFrame(d).T.reset_index()
df.columns = ['name','n1','n2']

Upvotes: 2

patelnisheet
patelnisheet

Reputation: 134

a={'iphone': [12, 21666], 'a1': [6, 5859], 'J5': [15, 13862]}
df = pd.DataFrame(a).T
df.reset_index(inplace=True)
df.columns = ['name','n1','n2']
print(df)

output:

     name  n1     n2
0  iphone  12  21666
1      a1   6   5859
2      J5  15  13862

reset index is require step without it, it will take ['iphone','a1','J5'] as a index

Upvotes: 0

Anshul Verma
Anshul Verma

Reputation: 377

You can give a try like this.

df = pd.DataFrame({'iphone': [12, 21666], 'a1': [6, 5859], 'J5': [15, 13862]})
df.columns = ["name", "n1", "n2"]
print(df)

Upvotes: 0

jezrael
jezrael

Reputation: 862511

Use list comprehension with DataFrame constructor:

d = {'iphone': [12, 21666], 'a1': [6, 5859], 'J5': [15, 13862]}

df = pd.DataFrame([([k] + v) for k, v in d.items()], columns=['name','n1','n2'])
#alternative
#df = pd.DataFrame([(k, *v) for k, v in d.items()], columns=['name','n1','n2'])
print (df)
     name  n1     n2
0  iphone  12  21666
1      a1   6   5859
2      J5  15  13862

General solution for list with all lenghts, not only 2:

df = pd.DataFrame([(k, *v) for k, v in d.items()])
#python 3.6+ with f-strings
df.columns = ['name'] + [f'n{x}' for x in df.columns[1:]]
#python bellow
#df.columns = ['name'] + ['n{}'.format(x) for x in df.columns[1:]]
print (df)
     name  n1     n2
0  iphone  12  21666
1      a1   6   5859
2      J5  15  13862

Or:

df = (pd.DataFrame.from_dict(d, orient='index')
                  .rename(columns=lambda x: x+1)
                  .add_prefix('n')
                  .rename_axis('name')
                  .reset_index())
print (df)
     name  n1     n2
0  iphone  12  21666
1      a1   6   5859
2      J5  15  13862

Upvotes: 4

Related Questions