-
Notifications
You must be signed in to change notification settings - Fork 0
/
dictionaries.py
71 lines (56 loc) · 1.46 KB
/
dictionaries.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
"""
Practice on dictonaries
"""
# To print specific key values
database = {'name':'Ken',
'age':38,
'gender': 'M',
'occupation': 'Teacher'}
print(database['name'], 'is a',
database['occupation'], 'and he is',
database['age'], 'years old')
# To print the whole dictonary
for key in database:
print(key, database[key])
# Using if method
if 'country' in database:
print(database['name'],'comes from',
database['country'])
# Using the get method
numbers = {'one': 1,
'two': 2,
'three': 3}
numbers.get('four', 'key missing')
# Creating a shopping one
shopping = {
'apples': 300,
'bread': 60,
'bananas':100,
'eggs': 360,
'milk':110
}
# Print prices less than input entered
price = int(input("What is your budget amount?"))
for key in shopping:
if shopping[key] <= price:
print(key, shopping[key])
total = 0
for key in shopping:
total = total + shopping[key]
print("This shopping will cost Ksh", total)
# More advanced shopping one using a while loop
myShopping = {}
total = 0
while True:
item = input('Enter an item:')
if item == "":
break
price = float(input('Enter the price:'))
myShopping[item] = price
for key in myShopping:
print(key, myShopping[key])
total = total + myShopping[key]
# More advanced shopping one using functions
def calculateTotal (d):
total = 0
print('Your shopping will cost', calculateTotal(myShopping))