0

I have the following list in python

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

I want to create the following dictionary

dayweek = {'Saturday': 1, 'Monday': 2, 'Thursday': 3, 'Friday': 4, 'Tuesday': 
5, 'Sunday': 6, 'Wednesday': 7}

I have tried the following code

     dayweek=dict(enumerate(days))

This yields the following result

  {0: 'Saturday', 1: 'Monday', 2: 'Thursday', 3: 'Friday', 4: 'Tuesday', 5: 
  'Sunday', 6: 'Wednesday'}

How do i accomplish the same

I request someone to help me

Raghavan vmvs
  • 1,097
  • 1
  • 9
  • 24

4 Answers4

3

You can give a starting value of 1 to enumerate and use a dictionary comprehension:

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

dayweek = { day:index for index, day in enumerate(days, 1)}
print(dayweek)

# {'Saturday': 1, 'Monday': 2, 'Thursday': 3, 'Friday': 4, 'Tuesday': 5, 'Sunday': 6, 'Wednesday': 7}
Thierry Lathuille
  • 22,718
  • 10
  • 38
  • 45
2

Just use a dictionary comprehension:

>>> m={d:i+1 for i,d in enumerate(days)}
>>> m
{'Saturday': 1, 'Monday': 2, 'Thursday': 3, 'Friday': 4, 'Tuesday': 5, 'Sunday': 6, 'Wednesday': 7}
cdarke
  • 40,173
  • 7
  • 78
  • 79
2

Try this :

dict(zip(days, range(1, len(days)+1)))

Output :

{'Monday': 2, 'Tuesday': 5, 'Friday': 4, 'Wednesday': 7, 'Thursday': 3, 'Sunday': 6, 'Saturday': 1}
khelili miliana
  • 3,537
  • 1
  • 14
  • 25
0

check this out:

dict([(j, i) for i, j in enumerate(days, 1)])
M.Rau
  • 554
  • 4
  • 10
  • 1
    You create an intermediate list before building a dict out of it, this is inefficient and much slower than using a dict comprehension, see my answer. Some timing: on my machine, the dict comprehension takes 1.66µs, your solution takes 3.08µs – Thierry Lathuille Aug 13 '18 at 09:28
  • makes sense. I typically do not dig into the details for 7 items but of cause Thierry is right. – M.Rau Aug 13 '18 at 09:47