python_math_stat/docs/python/dictionaries.md
2023-10-13 13:12:24 +03:00

70 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## Dictionaries
- Структура данных, кот. сод. __неупорядоч__ пос-ть различных о. КЛЮЧ + ЗНАЧЕНИЕ
- Добавление ключа (__НЕ__ может содержать одинаковых ключей, если добавить, то значение обновится)
```python
price = {'opel': 5000, 'toyota': 7000, 'bmw':10000}
price['mazda'] = 4000 -> #добавится в конце
```
```python
del.price['toyota'] #удаление переменной price
price.clear() #удаление ключей в перменной price
```
- Замена ключей в нескольких словарях
```python
person = {
'first name': 'Jack',
'last name' : 'Brown',
'age': 43,
'hobbies' : ['football', 'singing','photo'],
'children' : ['son':'Michael','daughter':'Pamela']
}
print (person['age'])
hobbies = person ['hobbies']
print(hobbies[2]) #то же == print(person['hobbies'][2])
```
Изменение э-та словаря по индексу `person['hobbies'][0]='basketball'`
- Методы с словарями:
`person.keys()` - получение ключей
`person.values()` - получения значений
`person.items()` - ключи + значений в виде картежа [('ключ','значение'),('ключ','значение')]
### Цикл `for` для dictionaries \
__`.items()`__ - и ключ и значения
```python
for items in dict.items():
print(item) -> ('key1','value1')
('key2','value2')
```
__`.keys()`__ - только ключи
```python
dict = {'key1':'value1','key2':'value2'}
for item in dict.keys():
print(key) -> key1
key2
```
__`.values()`__ - только значения
```python
dict = {'key1':'value1','key2':'value2'}
for item in dict.values():
print(values) -> value1
value2
```
### Dict comprehension
Работа со всеми эл-тами всех ключей
```python
num_dict = {'first':1,'second':2,'third':3}
new_dict = {key:value **3 for key,value in num_dict.items()} # создаем новый словарь с значением в 3 степени
print (new_dict) -> {'first':1,'second':8,'third':27} # т.к. если без .items() то раб только с ключами, чтобы оба .items()
```
```python
list = [6,43,-2,11,-55,-12,3,345]
num_dict = {number:number**2 for number in list} #ключ - это старый эл-т, value **3 - значение для ключа
print (num_dict) -> {6:36,43:1849,-2:4...}
```
```python
num_dict = {number: ('positive' if number >0),(else 'negative' if number <0),(else'zero') for number in list}
print (num_dict) -> {6:'positive', 43:'positive',-2:'negative'...}
```