Here's an organized summary of the information about different data structures in Python, along with methods to iterate over them as key-value pairs when applicable:
Feature by Data Structure
| Feature | Dictionary | Set | List | String | Tuple |
|---|---|---|---|---|---|
| Definition | Stores keypairs | An unordered collection of unique elements | A sequential, mutable collection of any data type | A sequential, immutable collection of textual data | A sequential, immutable collection of any data type |
| Representation | { 'a':[42], 'b':[23,6,1] } | {'^2', 'mc', 'equal', 'E'} | [ 'a','b', 3, 4 ] | "call me ishmael" | ( 'commander','lambda') |
| How to create? | x = {}, x = dict() | x = set() | x = [], x = list() | x = "", x = str() | x = ('a','b',), x = tuple() |
| Is structure mutable and allow duplicate elements? | Immutable keys but mutable and duplicate values | Mutable but unique elements only | Mutable and allows duplicate elements | Immutable but allows duplicate elements | Immutable but allows duplicate elements |
| Is the structure iterable? | Yes (iterable over keys) | Yes | Yes | Yes | Yes |
Methods and Iteration
Dictionary
- Methods:
items(),keys(),values() - Iteration:python
d = { 'a': [42], 'b': [23, 6, 1] } for key, value in d.items(): print(f"{key}: {value}")
Set
- Methods: No key-value methods, primarily
add(),remove(),union(), etc. - Iteration:python
s = {'^2', 'mc', 'equal', 'E'} for element in s: print(element)
List
- Methods: Index-based methods,
append(),extend(),insert(),remove(), etc. - Iteration:python
l = ['a', 'b', 3, 4] for index, value in enumerate(l): print(f"{index}: {value}")
String
- Methods: String-specific methods,
split(),join(),find(),replace(), etc. - Iteration:python
s = "call me ishmael" for index, char in enumerate(s): print(f"{index}: {char}")
Tuple
- Methods: Tuple-specific methods, mainly
count()andindex() - Iteration:python
t = ('commander', 'lambda') for index, value in enumerate(t): print(f"{index}: {value}")
Summary
- Dictionary: Best for key-value paired data, mutable values, and iterable over keys.
- Set: Ideal for unique, unordered data, mutable, but no key-value pairs.
- List: Great for ordered, mutable collections with duplicates allowed.
- String: Immutable text data, iterated as characters.
- Tuple: Immutable ordered collections, can contain duplicates.
No hay comentarios:
Publicar un comentario