-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_lookup.py
74 lines (55 loc) · 2.01 KB
/
reverse_lookup.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
74
def reverseLookup(dic, value):
"""
This program takes two arguments, a dictionary and a value
and tries to lookup the corresponding keys for the value.
@param: Dictionary
value - int, float, str etc.
@return: list of keys of type string.
"""
# Search for value in dictionary and return the key in a list if it exist.
return [k for k, v in dic.items() if v == value]
def create_dicts():
"""
This program returns a list containing automatically generated
dictionaries, ie. a list of dictionaries with the length of the
list being equal to num_cases.
@param: None
@return: List of dictionaries.
"""
import random
# Initialize state variables.
num_cases = 10
ind = 0
# Pre-allocate ls with zero placeholders.
ls = [0 for i in range(num_cases)]
for i in range(num_cases):
# Initialize variables.
dic_len = random.randrange(4, 7)
dic = dict()
for j in range(dic_len):
# Generate length of proposed key.
key_len = random.randrange(3, 5)
# Generate list of characters with length key_len.
key_list = [chr(random.randrange(ord('a'), ord('z'))) for i in range(key_len)]
# Convert key_list to string to get a random key.
key = ''.join(key_list)
# Generate a random value.
value = random.randrange(0, 5)
# Populate dic with key-value pair.
if key not in dic:
dic[key] = value
# Replace each zero placeholder with appropriate dic.
ls[ind] = dic
# Increment index.
ind += 1
# Return a list of dictionaries.
return ls
def main():
import random
# Generate dictionaries for testing.
for dic in create_dicts():
# Generate a value and lookup the keys.
value = random.randrange(0, 5)
print(f'\nDict: {dic}\nValue: {value} is mapped to {reverseLookup(dic, value)} keys')
if __name__ == "__main__":
main()