Рубрики
Без рубрики

Python в размере укус: Словари базовые

Базовое использование словарей типа данных в Python. Теги с Python.

Как подразумевает имя, словарь состоит из ключей и сопоставления значений, чтобы мы могли посмотреть на ценность используя ключ Точно так же мы обращаемся к значению слова.

Этот пост покажет некоторую базовую операцию по словарям, как создание словаря, модификация и так далее.

Давайте начнем!

Словарь Создание

# create empty list
>>> a_dict = {}
# or
>>> a_dict = dict()

# create with some value
# key's in the dictionary can be mix with some other types
>>> a_dict = {"key1": "value1", 2: "two", "three": 3} 
>>> a_dict
{'key1': 'value1', 2: 'two', 'three': 3}

# or using dict() with sequence of key-value pairs
# like list of a pair of tuple
>>> a_dict = dict([("key1", "value1"), (2, "two"), ("three", 3)])
>>> a_dict
{'key1': 'value1', 2: 'two', 'three': 3}

Доступ к значению словаря

# using the same manner of accessing list element 
# but use the key instead of index number
>>> a_dict["key1"]
'value1'
# or using get()
>>> a_dict.get(2)
'two'
# the main difference between these two is 
# get() will return None if the key is not found 
# in the dictionary but the other will raise the KeyError exception
# so, your program will break if the error's raise, so be careful
>>> a_dict.get("python")
>>> # noting happen

>>> a_dict["python"]
KeyError: 'python'

# you can check whether the key is available 
# in the dictionary or not using `in` syntax
>>> "key1" in a_dict
True
>>> "python" in a_dict
False

Словарь модификация

# modify the existing value
>>> a_dict["key1"] = "one"
>>> a_dict
{'key1': 'one', 2: 'two', 'three': 3}

# adding new key-value pair
>>> a_dict["python"] = "snake"
>>> a_dict
{'key1': 'one', 2: 'two', 'three': 3, 'python': 'snake'}

# delete using `del`
>>> del a_dict[2]
>>> a_dict
{'key1': 'one', 'three': 3, 'python': 'snake'}

Итализация по словарю

# we can iterate over dictionary using looping statement like `for-loop` with items() to get both key and value pair for each member
>>> for k, v in a_dict.items():
        print(k,":",v)
key1 : one
three : 3
python : snake

# getting keys only using keys()
>>> a_dict.keys() 
dict_keys(['key1', 2, 'three'])

# as you expect, we can get only values too!
>>> a_dict.values()
dict_values(['one', 3, 'snake'])

Я надеюсь, что это может помочь вам начать использовать словарь в Python.

Спасибо за прочтение!:)

Оригинал: “https://dev.to/phondanai/bite-size-python-dictionaries-basic-c4h”