Data structure in Python - list

names=['Peter', 'John']
size = ['X', 'M', 'L']
list_price = [1, 2, 3, 4, 5, 6] # There are 2 people will buy 3 size of shirt
I want to create my data structure into:
[
{'name': u'Peter', 'size_price': defaultdict(<type 'int'>, { 'X': 1, 'M':2, 'L': 3})},
{'name': 'John', 'size_price': defaultdict(<type 'int'>, {'X':4, 'M':5, 'L':6})}
]
I prefer to do defaultdict()

You can turn list_price into an iterator and then use next to get one value after the other:
>>> iterator = iter(list_price)
>>> [{"name": n, "size_price": {s: next(iterator) for s in size}} for n in names]
[{'size_price': {'X': 1, 'M': 2, 'L': 3}, 'name': 'Peter'},
{'size_price': {'X': 4, 'M': 5, 'L': 6}, 'name': 'John'}]
Of course you do not have to use a list comprehension but can do the same thing with nested loops as well.

Related

How can I add multiple object references of a class to a list in flutter?

I have some object references of a class like this:
Patient patientOne = Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true);
Patient patientTwo = Patient('Person B', 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTF8fGh1bWFufGVufDB8fDB8&ixlib=rb-1.2.1&w=1000&q=80',
8, 5, 'Cancel', '23-12-2019', false);
Patient patientThree = Patient('Person C', 'https://images.unsplash.com/photo-1554151228-14d9def656e4?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 7, 'Cancel', '01-02-2019', false);
Patient patientFour = Patient('Person D', 'https://upload.wikimedia.org/wikipedia/commons/e/ec/Woman_7.jpg',
8, 4, 'Pending', '20-09-2018', true);
Patient patientFive = Patient('Person E', 'https://cdn.pixabay.com/photo/2017/08/07/14/15/portrait-2604283__340.jpg',
8, 6, 'Pending', '28-04-2017', false);
I want to store those reference variables (patientOne , patientTwo ... patientFive ) into a list.
How to do that ?
final List<Patient> patients = <Patient>[];
patients.addAll([patientOne,patientTwo,patientThree,...]);
or
final List<Patient> patients = [
Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true),
Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true)
,...
] ;

X axis label in Highcharts graph in Django app

I have created Highcharts graph by this code:
def chart_data(request):
dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate(
c=Sum('weight')).values('month', 'c')
chart = {
'chart': {'type': 'column'},
'title': {'text': 'Weight Dispatched by Months'},
'series': [{
'name': 'Months',
'data': [{'name': row['month'], 'y': row["c"]} for row in dataset]
}]
}
return JsonResponse(chart)
How can I add the X axis labels such that it shows month name instead of 0 and 1 ?
This is the one row of dataset from which the graph is plotted
{'month': datetime.datetime(2019, 6, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>), 'c': 17600}
Try to use strftime (documentation) like that :
{'month': datetime.datetime(2019, 6, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>).strftime("%B"), 'c': 17600}

Plotting multiple pie charts in plotly

I have the following code from edited from: How to plot pie charts as subplots with custom size with Plotly in Python
import plotly
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected=True)
labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen']
values = [4500,2500,1053,500]
domains = [
{'x': [0.0, 0.33], 'y': [0.0, 0.50]},
{'x': [0.33, 0.66], 'y': [0.0, 0.50]},
{'x': [0.66, 1], 'y': [0.0, 0.50]},
{'x': [0.0, 0.33], 'y': [0.50, 1]},
{'x': [0.33, 0.66], 'y': [0.50, 1]},
{'x': [0.66, 1], 'y': [0.50, 1]},
]
traces = []
valueslist = []
for domain in domains:
trace = go.Pie(labels = labels,
values = values,
domain = domain)
traces.append(trace)
layout = go.Layout(height = 600,
width = 600,
autosize = False,
title = 'Main title')
fig = go.Figure(data = traces, layout = layout)
py.iplot(fig, show_link = False, image='png')
I am trying to plot 6 pie charts at one time with different values and different titles for each chart. How should I add these extra lists? Assume, I have the following lists to add:
values1 = [5, 6, 1, 2]
values2 = [1, 4, 5, 6]
values3 = [2, 6, 2, 4]
values4 = [1, 5, 3, 7]
values5 = [25, 51, 33, 47]
#with following titles:
title = 'title0'
title1 = 'title1'
title2 = 'title2'
title3 = 'title3'
title4 = 'title4'
title5 = 'title5'

Can I get 4 digit integer not string in python?

OUTPUT PHOTO
#### My work ####
from collections import OrderedDict
import json
test = {
'c': 2,
'B': '002',
'A': '{0:04d}'.format(2)
}
data = {'Author': "joe", 'data': test}
a = '{0:04d}'.format(2)
b=[1, a, '{0:04d}'.format(2)]
c = {1:a}
print (a, b, '{0:04d}'.format(2))
print(a)
print(b)
print(c)
print('{0:04d}'.format(2))
print json.dumps(data, indent=4, separators=(',', ': '))
#### Output
('0002', [1, '0002', '0002'], '0002')
0002
[1, '0002', '0002']
{1: '0002'}
0002
{
"data": {
"A": "0002",
"c": 2,
"B": "002"
},
"Author": "joe"
}
I'd like to get 0002 not "0002"
It is integer number when i use '{0:04d}'.format(2) in print().
but It is printed out as string if I put it in list or dictionary.
How can I get 4 digit number as integer type in dictionary?
Thanks

How to Append the values of ValueQuryset to array?

My View.py:
from django.db.models import Count
def test1(request):
states = Loksabha.objects.values('state').distinct('state')
terms = Loksabha.objects.values('term').distinct('term')
dataset = Loksabha.objects.all()
state_filter=Loksabha.objects.filter(state='Maharashtra',term='Fourteenth Lok Sabha(2004- 09)').annotate(num=Count('party',distinct=True))
age_filter=state_filter.values('party').annotate(Count('party'))
xdata=[]
ydata=[]
for b in state_filter:
xdata.append(b.party)
ydata.append(b.num)
chartdata = {'x': xdata, 'y': ydata}
charttype = "pieChart"
chartcontainer = 'piechart_container'
i have used django-nvd3 to display the graph my state_filter query answer is coreect but i cant understand the pass the value of ValueQueryset to xdata[] and ydata[]. my state_filter queryset value pass to the age_filter
age_filter value is:
[{'party': 'Shiv Sena', 'party__count': 14},
{'party': 'Indian Nationlist Congress', 'party__count': 15},
{'party': 'Nationlist Congress Party', 'party__count': 9},
{'party': 'Republican Party of India(A)', 'party__count': 1},
{'party': 'Bharatiya Janata Party', 'party__count': 14},
{'party': 'Independent', 'party__count': 1}]
ValueQuerySet yields dictionaries. Get items by indexing, instead of accessing attributes.
Replace following lines:
for b in state_filter:
xdata.append(b.party)
ydata.append(b.num)
with:
for d in age_filter:
xdata.append(b['party'])
ydata.append(b['party_count'])