Python Forum
Getting dictionary in the bokeh ColumnDataSource
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting dictionary in the bokeh ColumnDataSource
#1
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.
Yoriz write Sep-13-2022, 05:27 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
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
v_mn likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Bokeh help tangetjay 0 861 Jul-28-2022, 10:17 PM
Last Post: tangetjay

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020