How to transform a list of dictionary into a table

How to transform a list of dictionary into a table.

Here is the table:

[{'wow': 1,
  'item': 1,
  'money': 1},
 {'best': 1,
  'sock': 1,
  'saved': 1,
  'found': 1},
 {'cry': 1,
  'shock': 1,
  'sound': 1}]

Desired ouput:

words n
wow 1
item 1

I have tried

pd.DataFrame(x , columns=['Words', 'n'])

However, the output that I receive is just an index with empty columns.

Any help?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use pandas melt

x = [{'wow': 1,
  'item': 1,
  'money': 1},
 {'best': 1,
  'sock': 1,
  'saved': 1,
  'found': 1},
 {'cry': 1,
  'shock': 1,
  'sound': 1}]

df = pd.DataFrame(x)
df = df.melt().dropna().reset_index(drop=True)
df.columns = ['words', 'n']

Output:

How to transform a list of dictionary into a table

Method 2

You can use pd.columns

An example which you can refer to:

df = pd.DataFrame(someInput)
headers = ["Words", "n"]
df.columns = headers

Method 3

Chaining items of these dictionaries to build may meet your requirements:

>>> x = [{'wow': 1,
...   'item': 1,
...   'money': 1},
...  {'best': 1,
...   'sock': 1,
...   'saved': 1,
...   'found': 1},
...  {'cry': 1,
...   'shock': 1,
...   'sound': 1}]
>>> from itertools import chain
>>> pd.DataFrame(chain.from_iterable(d.items() for d in x), columns=['words', 'n'])
   words  n
0    wow  1
1   item  1
2  money  1
3   best  1
4   sock  1
5  saved  1
6  found  1
7    cry  1
8  shock  1
9  sound  1

Method 4

You could just chain the .items() while constructing the dataframe:

records = [
    {'wow': 1, 'item': 1, 'money': 1},
    {'best': 1, 'sock': 1,'saved': 1, 'found': 1},
    {'cry': 1, 'shock': 1, 'sound': 1}
]

df = pd.DataFrame((item for record in records for item in record.items()),
                  columns=["Word", "n"])

Result:

    Word  n
0    wow  1
1   item  1
2  money  1
3   best  1
4   sock  1
5  saved  1
6  found  1
7    cry  1
8  shock  1
9  sound  1

Method 5

I hope this code help

  tbl = [{'wow': 1, 'item': 1, 'money': 1}, {'best': 1, 'sock': 1, 'saved': 1, 'found': 1}, {'cry': 1, 'shock': 1, 'sound': 1}] 
  dicts = {}
  for d in tbl:
    dicts.update(d)

  df = pd.DataFrame.from_dict(dict(word=list(dicts.keys()), n=list(dicts.values())))


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x