Python Forum
Getting dictionary in the bokeh ColumnDataSource - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Getting dictionary in the bokeh ColumnDataSource (/thread-38187.html)



Getting dictionary in the bokeh ColumnDataSource - v_mn - Sep-13-2022

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.


RE: Getting dictionary in the bokeh ColumnDataSource - deanhystad - Sep-15-2022

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