- Python — Access Dictionary Items
- Example
- Example
- Get Keys
- Example
- Example
- Get Values
- Example
- Example
- Example
- Get Items
- Example
- Example
- Example
- Check if Key Exists
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Dictionaries
- dict ionary cheat sheet
- Examples
- Empty dict s
- Creating dict s with items
- Side note: What can be used as keys?
- Accessing
- Adding, Removing
- Updating
- Complex Dictionaries
- Working with items , keys , and values
- 1. my_dict.keys() Getting all the keys in a dictionary
- 2. my_dict.values() Getting all the values in a dictionary.
- 3. my_dict.items() Getting all the items (key, value pairs) in a dictionary
- Словари (dict) и работа с ними. Методы словарей
- Методы словарей
Python — Access Dictionary Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the «model» key:
There is also a method called get() that will give you the same result:
Example
Get the value of the «model» key:
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.
Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:
Get Values
The values() method will return a list of all the values in the dictionary.
Example
The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.
Example
Make a change in the original dictionary, and see that the values list gets updated as well:
Example
Add a new item to the original dictionary, and see that the values list gets updated as well:
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs
The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary will be reflected in the items list.
Example
Make a change in the original dictionary, and see that the items list gets updated as well:
Example
Add a new item to the original dictionary, and see that the items list gets updated as well:
Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:
Example
Check if «model» is present in the dictionary:
thisdict = <
«brand»: «Ford»,
«model»: «Mustang»,
«year»: 1964
>
if «model» in thisdict:
print(«Yes, ‘model’ is one of the keys in the thisdict dictionary»)
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Dictionaries
Dictionaries are a useful type that allow us to store our data in key, value pairs. Dictionaries themselves are mutable, but, dictionary keys can only be immutable types.
We use dictionaries when we want to be able to quickly access additional data associated with a particular key. A great practical application for dictionaries is memoization. Let’s say you want to save computing power, and store the result for a function called with particular arguments. The arguments could be the key, with the result stored as the value. Next time someone calls your function, you can check your dictionary to see if the answer is pre-computed.
Looking for a key in a large dictionary is extremely fast. Unlike lists, we don’t have to check every item for a match.
dict ionary cheat sheet
type | dict |
---|---|
use | Use for storing data in key, value pairs. Keys used must be immutable data types. |
creation | <> or dict() for an empty dict . for a dict with items. |
search methods | key in my_dict |
search speed | Searching for a key in a large dictionary is fast. |
common methods | my_dictPython словарь get key to get the value by key , and throw a KeyError if key is not in the dictionary. Use my_dict.get(key) to fail silently if key is not in my_dict . my_dict.items() for all key, value pairs, my_dict.keys() for all keys, and my_dict.values() for all values. |
order preserved? | Sort of. As of Python 3.6 a dict is sorted by insertion order. Items can’t be accessed by index, only by key. |
mutable? | Yes. Can add or remove keys from dict s. |
in-place sortable? | No. dict s don’t have an index, only keys. |
Examples
Empty dict s
We already learned one of the methods of creating an empty dict when we tried (and failed) to create an empty set with <> . The other way is to use the dict() method.
>>> my_dict = <> >>> type(my_dict) >>> my_dict = dict() >>> type(my_dict)
Creating dict s with items
If we want to create dict s with items in them, we need to pass in key, value pairs. A dict is declared with curly braces <> , followed by a key and a value, separated with a colon : . Multiple key and value pairs are separated with commas , .
We can call familiar methods on our dictionary, like finding out how many key / value pairs it contains with the built-in len(my_dict) method.
Side note: What can be used as keys?
Any type of object, mutable or immutable, can be used as a value but just like set s, dict ionaries can only use immutable types as keys. That means you can use int , str , or even tuple as a key, but not a set , list , or other dict ionary.
You’ll see a TypeError: unhashable type: ‘list’ if you try to use a mutable type, like a list as a dict ionary key.
>>> my_dict = <[]: 1>Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list'
Accessing
Our dict contains key , value pairs. Because a dict ionary isn’t ordered, we can’t access the items in it by position. Instead, to access the items in it, we use square-bracket my_dictPython словарь get key notation, similar to how we access items in a list with square bracket notation containing the position.
>>> nums = >>> nums[1] 'one' >>> nums[2] 'two'
Q: What happens when we try to access a key in a dict ionary with square bracket notation, but the key isn’t present?
We’ll get a KeyError: key if we try to access my_dictPython словарь get key with square bracket notation, but key isn’t in the dictionary.
>>> nums = >>> nums[4] Traceback (most recent call last): File "", line 1, in KeyError: 4
One way to get around this is to use the my_dict.get(key) method. Using this method, if the key isn’t present, no error is thrown, and no value (aka the None type) is returned.
>>> nums = >>> nums.get(4) >>> result = nums.get(4) >>> type(result)
If we want to provide a default value if the key is missing, we also pass an optional argument to the my_dict.get(key) method like so: my_dict.get(key, default_val)
>>> nums = >>> nums.get(4, "default") 'default'
Adding, Removing
To add a new key value pair to the dictionary, you’ll use square-bracket notation.
If you try to put a key into a dictionary that’s already there, you’ll just end up replacing it. To avoid subtle bugs, you can check if a particular key is in a dictionary with the in keyword. We’ll cover that technique in Chapter 6 — Control Statements and Looping.
>>> nums = >>> nums[8] = "eight" >>> nums >>> nums[8] = "oops, overwritten" >>> nums >>> 8 in nums True
Updating
Just like with list s an set s, you can update the items in a dictionary with the items from another dictionary.
>>> colors = >>> numbers = >>> colors.update(numbers) >>> colors
Complex Dictionaries
One incredibly useful scenario for dictionaries is storing the values in a list or other sequence. Going into too much detail is outside of the scope of the class, but I’ll show you a quick example:
>>> colors = >>> colors >>> colors["Green"].append("Apples") >>> colors
Working with items , keys , and values
There are three useful methods you need to remember about dict ionary access:
1. my_dict.keys() Getting all the keys in a dictionary
>>> nums = >>> nums.keys() dict_keys([1, 2, 3, 8])
2. my_dict.values() Getting all the values in a dictionary.
>>> nums = >>> nums.values() dict_values(['one', 'two', 'three', 'eight'])
3. my_dict.items() Getting all the items (key, value pairs) in a dictionary
Notice that my_dict.items() returns a type that looks like a list. It contains two-item tuple s containing the key, value pairs.
>>> nums = >>> nums.items() dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (8, 'eight')])
Словари (dict) и работа с ними. Методы словарей
Сегодня я расскажу о таком типе данных, как словари, о работе со словарями, операциях над ними, методах, о генераторах словарей.
Словари в Python — неупорядоченные коллекции произвольных объектов с доступом по ключу. Их иногда ещё называют ассоциативными массивами или хеш-таблицами.
Чтобы работать со словарём, его нужно создать. Сделать это можно несколькими способами. Во-первых, с помощью литерала:
Во-вторых, с помощью функции dict:
В-третьих, с помощью метода fromkeys:
В-четвертых, с помощью генераторов словарей, которые очень похожи на генераторы списков.
Теперь попробуем добавить записей в словарь и извлечь значения ключей:
: Как видно из примера, присвоение по новому ключу расширяет словарь, присвоение по существующему ключу перезаписывает его, а попытка извлечения несуществующего ключа порождает исключение. Для избежания исключения есть специальный метод (см. ниже), или можно перехватывать исключение.
Что же можно еще делать со словарями? Да то же самое, что и с другими объектами: встроенные функции, ключевые слова (например, циклы for и while), а также специальные методы словарей.
Методы словарей
dict.clear() — очищает словарь.
dict.copy() — возвращает копию словаря.
classmethod dict.fromkeys(seq[, value]) — создает словарь с ключами из seq и значением value (по умолчанию None).
dict.get(key[, default]) — возвращает значение ключа, но если его нет, не бросает исключение, а возвращает default (по умолчанию None).
dict.items() — возвращает пары (ключ, значение).
dict.keys() — возвращает ключи в словаре.
dict.pop(key[, default]) — удаляет ключ и возвращает значение. Если ключа нет, возвращает default (по умолчанию бросает исключение).
dict.popitem() — удаляет и возвращает пару (ключ, значение). Если словарь пуст, бросает исключение KeyError. Помните, что словари неупорядочены.
dict.setdefault(key[, default]) — возвращает значение ключа, но если его нет, не бросает исключение, а создает ключ со значением default (по умолчанию None).
dict.update([other]) — обновляет словарь, добавляя пары (ключ, значение) из other. Существующие ключи перезаписываются. Возвращает None (не новый словарь!).
dict.values() — возвращает значения в словаре.
Для вставки кода на Python в комментарий заключайте его в теги