Home > Back-end >  Printing number of days repeated Loop
Printing number of days repeated Loop

Time:12-16

I am a little confused I want to check how many times a value has repeated in a list of days. For example I have a dictionary

dict = {
  "01" : 0,
  "02" : 0,
  "03" : 0,
  "04" : 0,
  "05" : 0,
  "06" : 0,
  "07" : 0,
}

I have a list of values = ['02','01','02','03','07','05']

and I want to print result like this:

{"Monday": 1,"Tuesday": 2,"Wednesday": 1, "Thursday": 0, "Friday": 1, "Saturday": 0 ,"Sunday": 1}

Here is the code that I am testing

for i in range(len(value_list)):
  for j in day:
      print(j)

for i in range(len(value_list)):
   print(day.key)
   # count = value_list.count(list(day)[i])
  if value_list[i] == (day):
    print("i: ", value_list[i])

CodePudding user response:

I have created a new dictionary called days_of_week and changed the content of your dict in a way that each day is referred by a number, so when you iterate through the list of values and find a day it increments the counter for the specific day

Code:

days_of_week = {"Monday": 0, "Tuesday": 0, "Wednesday": 0,
                "Thursday": 0, "Friday": 0, "Saturday": 0, "Sunday": 0}
values = ['02', '01', '02', '03', '07', '05']
dict = {"01": 'Monday', "02": 'Tuesday', "03": 'Wednesday', "04": 'Thursday', "05": 'Friday', "06": 'Saturday', "07": 'Sunday'}
for val in values:
    if val in dict:
        days_of_week[dict[val]] =1
print(days_of_week)

Output:

{'Monday': 1, 'Tuesday': 2, 'Wednesday': 1, 'Thursday': 0, 'Friday': 1, 'Saturday': 0, 'Sunday': 1}

CodePudding user response:

For easy explanation, your question boils down into 2 parts: (1) Count existences in values and (2) Rename "0{1,2,3,4,5,6,7}" into {Mon, Tue, ...}

(1) Count values with the dictionary

for v in values:
    dict[v]  = 1

(2) Create a new dictionary with same values but renamed keys

orig_keys = [f"{i:02d}" for i in range(1,8)]
new_keys = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
new_dict = {}
for ok, nk in zip(orig_keys, new_keys):
    v = dict[ok]
    new_dict[nk] = v
print(new_dict)

Output

{'Monday': 1, 'Tuesday': 2, 'Wednesday': 1, 'Thursday': 0, 'Friday': 1, 'Saturday': 0, 'Sunday': 1}
  • Related