'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?



Solution 1:[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:

enter image description here

Solution 2:[2]

You can use pd.columns

An example which you can refer to:

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

Solution 3:[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

Solution 4:[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

Solution 5:[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())))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dat Boi
Solution 3
Solution 4 Timus
Solution 5 H.asadi