how to order a dictionary based on key by daywise in python

687 views Asked by At

I had 2 list

daydate=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

percentday=['0%', '17%', '27%', '11%', '7%', '19%', '19%']

i have converted into dictionary by doing

daydic=dict(zip(daydate, percentday))

the output is coming like

{'Monday': '17%', 'Tuesday': '27%', 'Friday': '19%', 'Wednesday': '11%', 'Thursday': '7%', 'Sunday': '0%', 'Saturday': '19%'}

i want to sort this dictionary like the order of elements in daywise like below

{'Sunday': '0%','Monday': '17%', 'Tuesday': '27%', 'Wednesday': '11%', 'Thursday': '7%', , 'Friday': '19%','Saturday': '19%'}

Help me

3

There are 3 answers

0
jpp On

Dictionaries should not be considered ordered

They are, in fact, insertion ordered in Python 3.6+ (officially 3.7+), but even so you should prefer to use OrderedDict for a robust ordered mapping.

In addition, you should never have to type days of the week manually, you can import from calendar.day_name and rotate via deque:

from calendar import day_name
from collections import deque, OrderedDict

daydate = deque(day_name)
daydate.rotate(1)

percentday = ['0%', '17%', '27%', '11%', '7%', '19%', '19%']

res = OrderedDict(zip(daydate, percentday))

OrderedDict([('Sunday', '0%'),
             ('Monday', '17%'),
             ('Tuesday', '27%'),
             ('Wednesday', '11%'),
             ('Thursday', '7%'),
             ('Friday', '19%'),
             ('Saturday', '19%')])
2
iGian On

As told, a dict is not ordered, but you can order before to convert to dict.

daydate=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
percentday=['0%', '17%', '27%', '11%', '7%', '19%', '19%']

Sort by day, just rotate the zip:

dayzip = list(zip(daydate, percentday))
dayzip = dayzip[1-len(dayzip):] + dayzip[:1-len(dayzip)]
daydict = dict(dayzip)

#=> {'Sunday': '0%', 'Monday': '17%', 'Tuesday': '27%', 'Wednesday': '11%', 'Thursday': '7%', 'Friday': '19%', 'Saturday': '19%'}

To sort by percentage:

dayzip = list(zip(daydate, percentday))
dayzip.sort(key=lambda x: float(x[1][:-1]) )
daydict = dict(dayzip)


#=> [('Sunday', '0%'), ('Monday', '17%'), ('Tuesday', '27%'), ('Wednesday', '11%'), ('Thursday', '7%'), ('Friday', '19%'), ('Saturday', '19%')]
#=> {'Sunday': '0%', 'Thursday': '7%', 'Wednesday': '11%', 'Monday': '17%', 'Friday': '19%', 'Saturday': '19%', 'Tuesday': '27%'}
0
Somya Avasthi On

You can try this:

from collections import OrderedDict
daydic={'Friday': '19%', 'Wednesday': '11%', 'Monday': '17%', 'Thursday': '7%', 'Saturday': '19%', 'Sunday': '0%', 'Tuesday': '27%'}
weeks=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
print(OrderedDict(sorted(daydic.items(),key =lambda x:weeks.index(x[0]))))

This will output as:

OrderedDict([('Sunday', '0%'), ('Monday', '17%'), ('Tuesday', '27%'), ('Wednesday', '11%'),
 ('Thursday', '7%'), ('Friday', '19%'), ('Saturday', '19%')])