Python Forum

Full Version: Getting dictionary in the bokeh ColumnDataSource
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a dictionary as below:

d={0:[{'key':'apple', 'count':50},{'key':'ibm', 'count':25}],
1: [{'key':'apple', 'count':40},{'key':'ibm', 'count':29}],
2:[{'key':'apple', 'count':44},{'key':'ibm', 'count':21}]}
I want a bar plot but I have difficulty first reading it.

from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn
from bokeh.layouts import widgetbox, column
from bokeh.io import output_file, show

source = ColumnDataSource(d)

columns = [
        TableColumn(field="key", title="Brand"),
        TableColumn(field="count", title="Count")
    ]
data_table = DataTable(source=source, columns=columns, width=400, height=280)

plot = column(widgetbox(data_table))

show(plot)

I want the result as below:
https://imgur.com/5H9A2fv
So I think getting the table is quite complicated.
Having two levels of dictionaries makes this tricky (for me anyway).
import pandas as pd

d = {
       0:[{'key':'apple', 'count':50},{'key':'ibm', 'count':25}],
       1:[{'key':'apple', 'count':40},{'key':'ibm', 'count':29}],
       2:[{'key':'apple', 'count':44},{'key':'ibm', 'count':21}]
}

dlist = []
for index, values in d.items():
       row = {"index":index}
       row.update({value["key"]:value["count"] for value in values})
       dlist.append(row)

df = pd.DataFrame.from_dict(dlist)
print(df)
Output:
index apple ibm 0 0 50 25 1 1 40 29 2 2 44 21
If you don't need the index column it can be done with in one line.
import pandas as pd

d = {
       0:[{'key':'apple', 'count':50},{'key':'ibm', 'count':25}],
       1:[{'key':'apple', 'count':40},{'key':'ibm', 'count':29}],
       2:[{'key':'apple', 'count':44},{'key':'ibm', 'count':21}]
}

dlist = [{value["key"]:value["count"] for value in values} for values in d.values()]

df = pd.DataFrame.from_dict(dlist)
print(df)
Output:
apple ibm 0 50 25 1 40 29 2 44 21