-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModule_2_Counters_Object.py
73 lines (63 loc) · 2.48 KB
/
Module_2_Counters_Object.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# 34567890123456789012345678901234567890123456789012345678901234567890123456789
# 3456789012345678901234567890123456789012345678901234567890123456789012
# Homework:
# Write a code, which will:
# 1. create a list of random number of dicts (from 2 to 10)
# dict's random numbers of keys should be letter,
# dict's values should be a number (0-100),
# example:[{'a': 5, 'b': 7, 'g': 11}, {'a': 3, 'c': 35, 'g': 42}]
# import module random to get randint
import random
import string
# var for random number of dicts (from 2 to 10)
rdic = random.randint(2, 10)
# var list of random number of dicts
lis = []
# this part for list of random number of dicts (from 2 to 10)
for i in range(rdic):
# English alphabet length
g = random.randint(1, 26)
d = {}
for k in range(g):
# random word from English alphabet as key
d.setdefault(random.choice(string.ascii_lowercase),
random.randint(0, 100))
lis.append(d)
# print(lis)
# 2. get previously generated list of dicts and create one common dict:
# if dicts have same key, we will take max value, and rename key with
# dict number with max value
# if key is only in one dict - take it as is,
# example:{'a_1': 5, 'b': 7, 'c': 35, 'g_2': 42}
# temporary dicts
tempdict = {}
dictnumber = {}
# iterating over the list
for i in range(len(lis)):
# iterating over the dicts in the list
for key, value in lis[i].items():
# check if the key is in the tempdict - if not, insert it
if key in tempdict.keys():
# if the key in the dict and its value is more than in
# the dictionary - delete the old value in the
# dictionary and insert a new one
if value > tempdict.get(key):
# a separate dictionary where we collect duplicate
# keys and numbers of the largest dictionary number
if key in dictnumber.keys():
dictnumber.pop(key)
dictnumber.setdefault(key, i)
else: dictnumber.setdefault(key, i)
tempdict.pop(key)
tempdict.setdefault(key, value)
else: tempdict.setdefault(key, value)
# print(tempdict)
# print(tempdict.keys())
# print(dictnumber)
finaldict = {}
# merge two dicts
for key, value in tempdict.items():
if key in dictnumber.keys():
finaldict.setdefault(key +'_' + str(dictnumber.get(key)), value)
else: finaldict.setdefault(key, value)
print(finaldict)