1
0
mirror of https://github.com/onkelbeh/cheatsheets.git synced 2025-06-14 22:27:33 +02:00

Python: add Set and modify Dict (#2163)

This commit is contained in:
Nick Korostelev 2024-09-24 06:23:27 -07:00 committed by GitHub
parent 746bae2ebe
commit 1fa8ae160f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -46,15 +46,28 @@ sorted(list) # returns sorted copy of list
```py
dict = {}
dict = {'a': 1, 'b': 2}
dict['c'] = 3
del dict['a'] # Remove key-value pair with key 'c'
dict.keys()
dict.values()
"key" in dict # let's say this returns False, then...
dict["key"] # ...this raises KeyError
dict.get("key") # ...this returns None
dict["key"] # if "key" not in dict raises KeyError
dict.get("key") # if "key" not in dict returns None
dict.get("key", "optional return value if no key")
dict.setdefault("key", 1)
**dict # expands all k/v pairs in place
```
### Set
```py
set = set()
set = {1, 2, 3}
set.add(4)
set.remove(2)
```
### Iteration
```py