Dictionary type A dictionary type is a data type that manages a set of data together with an identifier called a "key" and the corresponding "value". Tuples are created in "()" parentheses, lists are created in "[]" brackets, but dictionaries use "{}" wave brackets. To create an object, write as follows.
hatamoto = {"kokugo":65,"suugaku":82,"eigo":70"} Separate it from the next element with ",". I recognize that it is used like a table operation in SQL.
dict()
hatamoto = {"kokugo”:65,”suugaku”:82,”eigo”:70} print( hatamoto)
Execution result:
{"kokugo":65,"suugaku":82,"eigo":70"}
You can also copy using dict ().
hatamoto = {"kokugo":65,"suugaku":82,"eigo":70"} hatamoto2 = dict(hatamoto) print(hatamoto2)
{"kokugo”:65,”suugaku”:82,”eigo”:70}
A dictionary with the same key and value is created.
len() You can check the length of the Python dictionary with len, just like a list.
hatamoto = {"kokugo":65,"suugaku":82,"eigo":70"} len(hatamoto)
Execution result:
3
update()
Dictionary .update (dictionary to combine)
hatamoto = {"kokugo":65,"suugaku":82,"eigo":70"} hatamoto2 = {"rika":"90", "syakai":"51"} hatamoto.update(hatamoto2) print(hatamoto)
Execution result: {'kokugo':'65','suugaku':'82','eigo':70,'rika':'90','syakai':'51'}
If you specify a new key, an item will be added, and if you specify an existing one, it will be overwritten.
Delete element by specifying key
hatamoto = {"kokugo":65,"suugaku":82,"eigo":70"}
del hatamoto['kokugo'] print(hatamoto)
Execution result:
{'suugaku':'82','eigo':'70'}
If you specify a key that does not exist, a "Key Error" will occur.
keys() Get all the keys
hatamoto = {"kokugo":65,"suugaku":82,"eigo":70"} print(hatamoto.keys())
dict_keys(['kokugo', 'suugaku', 'eigo'])
Recommended Posts