Dictionaries (Wörterbücher)
Wörterbuch
[auch Hash-Tabelle, Karte oder Objekte genannt.]
Ein Wörterbuch ist ein ungeordnetes Schlüssel-Wert-Paar. Es kann ein String, ein Int, ein Boolescher Wert oder ein Tupel sein, aber meistens werden Stiche berücksichtigt Sie können keine Listen haben oder als Wörterbuch festlegen, da diese unveränderlich sind Ein Schlüssel in einem Wörterbuch muss eindeutig sein
dictionary = {
"key": 'value',
'a': 1,
'b': [1, 2, 3],
'c': 'hello',
'd': True
}
print(dictionary['b'][1])
user = {
'basket': [1, 2, 3],
'greet': 'hello',
'age': 22
}
print(user.get('age')) # returns None this is used to avoid error
print(user.get('age', 22)) # returns 22 [adds default value]
Eine andere Möglichkeit, ein Wörterbuch zu erstellen
user2 = dict(name='Marwa')
print(user2)
Eine andere Möglichkeit, Dinge im Diktat anzuzeigen
print('basket' in user)
Methoden in dict
print('greet' in user.keys()) # returns True if it exists
print('hello' in user.values()) # returns True if it exists
print(user.items()) # shows all items in dictionary
user2 = user.copy() # copies the keys and values
print(user2)
# Updates the item[if does'nt exist adds new item]
print(user.update({'age': 23}))
print(user.pop("age")) # pop off age value
print(user.popitem()) # pops off last item
print(user.clear()) # clears the dict
Wörterbuch innerhalb einer Liste
my_list = [
{
"key": 'value',
'a': 1,
'b': [1, 2, 3],
'c': 'hello',
'd': True
},
{
"key": 'value',
'a': 2,
'b': [4, 5, 6],
'c': 'hi',
'd': False
}]
print(my_list[0]['b'][1])