After a few months of break from blogging and, above all, coding in Python, I wanted to remind myself how to use Dictionaries in this programming language. I took refresher lessons based on my own materials available here: Sets & Dictionaries, but also by chatting with ChatGPT
#Dic example
person = {
"name": "Agnieszka",
"age": 18,
"country": "Poland",
"city": "Olsztyn"
}
# basic ops
print(person)
print(person["name"])
print(person.get("age"))
person["age"] = 27
print(person)
person["sex"] = "woman"
print(person)
del person["city"]
print(person)
#loops
for key in person:
print(key)
for value in person.values():
print(value)
for key, value in person.items():
print(f"{key}:{value}")
#check, if name is in dict
if "name" in person:
print("Name is present")
elif "name" not in person:
print("Not present")
else:
print("nothing")
#result: Name is present
#check, if color is in dict and name is not
if "color" in person:
print("Name is present")
elif "name" not in person:
print("Not present")
else:
print("nothing")
#result: nothing
#check, if color is in person or is not
if "color" in person:
print("Name is present")
elif "color" not in person:
print("Not present")
else:
print("nothing")
#result: Not present
#Nasted Dictionaries
animals = {
"cats":{
"name": "Sweetie",
"age": "12",
"color": "black"
},
"dogs": {
"name": "Jack",
"age": "9",
"color": "brown"
}
}
print(animals["cats"]["name"])
print(animals["dogs"]["color"])
print(animals["cats"]["age"],animals["dogs"]["name"])
#ops on dicts with ranges
numbers = {x:x for x in range(0,9)}
print(numbers)
numbers = {x:x*2 for x in range(0,9)}
print(numbers)
numbers = {x:(x*2)/(x+1) for x in range(0,9)}
print(numbers)
#update, sum in
dict1 = {x:x for x in range(0,3)}
dict2 = {y:y for y in range(2,5)}
print(dict1)
print(dict2)
dict1.update(dict2)
print(dict1)
combined_dict = {**dict1, **dict2}
print(combined_dict)
#merging dictionaries
D1 = dict(name = "Aga", age = 35, year = 1989, hobby = "dance")
#print(D1)
D2 = dict(name = "Kuba", age = 41, year = 1984, hobby = "soccer")
D3 = {**D1,**D2}
print(D3)
#output:for same keys we will get values from second dict:
#{'name': 'Kuba', 'age': 41, 'year': 1984, 'hobby': 'soccer'}
D1 = dict(name = "Aga", age = 35, year = 1989, hobby = "dance")
#print(D1)
D2 = dict(zodiac = "Cancer", hair = "brown", sex = "woman")
D3 = {**D1,**D2}
print(D3)
#output:
#{'name': 'Aga', 'age': 35, 'year': 1989, 'hobby': 'dance', \
# 'zodiac': 'Cancer', 'hair': 'brown', 'sex': 'woman'}
#counting letters
text= "welcome really really fat fat Joe"
word_count = {}
for word in text.split():
word_count[word]= word_count.get(word,0) +1
print(word_count)