If objective is to get data into dataframe then there are also following alternatives:
- using
.from_dict
and
.append
:
first = {"name": "fred", "age" : 31}
second = {"name": "bob", "age" : 35}
df = pd.DataFrame.from_dict([first],
orient="columns").append(pd.DataFrame.from_dict([second]), ignore_index=True)
# df would be:
name age
0 fred 31
1 bob 35
However, this is long, ugly and append method is deprecated. Same result can be achieved using
concat
df_x = pd.DataFrame.from_dict([first],orient="columns")
df_y = pd.DataFrame.from_dict([second], orient="columns")
df = pd.concat([df_x, df_y], ignore_index=True)
Same problems as with first example. This is not scalable, it works only in case of two dictionaries. For arbitrary number of dictionaries they must be in container. Then we can create stream (generator) and feed it to concat:
persons = [{"name": "fred", "age": 31},
{"name": "bob", "age": 35},
{"name": "alice", "age": 33}]
stream = (pd.DataFrame.from_dict((person,), orient="columns") for person in persons)
df = pd.concat(stream, ignore_index=True)
# df would be
name age
0 fred 31
1 bob 35
2 alice 33