|
| 1 | +# Why not have some fun with Dictionaries. Try these |
| 2 | +# Python program examples to get a feel of how dictionaries |
| 3 | +# in Python work and how useful they truly are in programs. |
| 4 | + |
| 5 | +# Let's create an animals dictionary so we can use its values. |
| 6 | + |
| 7 | +animals={ |
| 8 | + 'Dog':'Wolf', |
| 9 | + 'Cat':'Lion', |
| 10 | + 'Bird':'Eagle', |
| 11 | + 'Fish':'Shark' |
| 12 | + } |
| 13 | + |
| 14 | +print(animals.get('dog')) |
| 15 | +print(animals.get('dog','Not Found!')) |
| 16 | +print(animals.get('Dog','Not Found!')) |
| 17 | + |
| 18 | +for key,value in animals.items(): |
| 19 | + print(key) |
| 20 | + |
| 21 | +for key,value in animals.items(): |
| 22 | + print(value) |
| 23 | + |
| 24 | +for key,value in animals.items(): |
| 25 | + print(key,value) |
| 26 | + |
| 27 | +# Let's create some sentences out of our animals dictionary list. |
| 28 | + |
| 29 | +d=animals.get('Dog') |
| 30 | +c=animals.get('Cat') |
| 31 | +b=animals.get('Bird') |
| 32 | +f=animals.get('Fish') |
| 33 | + |
| 34 | +print(f'My dog is really a {d}.') |
| 35 | +print(f'My Cat is really a {c}.') |
| 36 | +print(f'My Bird is really a {b}.') |
| 37 | +print(f'My Fish is really a {f}.') |
| 38 | + |
| 39 | +# Let's create some sentences out of our animals dictionary list |
| 40 | +# using a 'for in' items() function to drastically reduce lines of |
| 41 | +# code and code redundancy in our Python program example. |
| 42 | + |
| 43 | +for keys,values in animals.items(): |
| 44 | + print(f'My {keys} is really a {values}.') |
| 45 | + |
| 46 | +# Rename the key and value variables if you wish. |
| 47 | + |
| 48 | +for my_keys,my_values in animals.items(): |
| 49 | + print(f'My {my_keys} is really a {my_values}.') |
| 50 | + |
| 51 | +for animal_keys,animal_values in animals.items(): |
| 52 | + print(f'My {animal_keys} is really a {animal_values}.') |
| 53 | + |
| 54 | +# Try this dictionary Python program example below and recap |
| 55 | +# what happens when you type and execute/run this program. |
| 56 | + |
| 57 | +animals={ |
| 58 | + 'Dog':'Wolf', |
| 59 | + 'Cat':'Lion', |
| 60 | + 'Bird':'Eagle', |
| 61 | + 'Fish':'Shark'} |
| 62 | + |
| 63 | +people={ |
| 64 | + 'Person1':'John', |
| 65 | + 'Person2':'Bob', |
| 66 | + 'Person3':'Rob', |
| 67 | + 'Person4':'Tom'} |
| 68 | + |
| 69 | +for key,value in animals.items(): |
| 70 | + print(key,value) |
| 71 | + |
| 72 | +for key,value in people.items(): |
| 73 | + print(key,value) |
0 commit comments