Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- """
- from collections import namedtuple
- # Defining a namedtuple
- Person = namedtuple('Person', ['name', 'age', 'city'])
- # Creating instances of namedtuple
- person1 = Person(name='Alice', age=25, city='New York')
- person2 = Person(name='Bob', age=30, city='Los Angeles')
- # Accessing fields
- print(person1.name) # Output: Alice
- print(person1.age) # Output: 25
- print(person1.city) # Output: New York
- # Accessing fields by index
- print(person2[0]) # Output: Bob
- print(person2[1]) # Output: 30
- print(person2[2]) # Output: Los Angeles
- # Accessing fields using _fields attribute
- print(person1._fields) # Output: ('name', 'age', 'city')
- # Converting namedtuple to a dictionary
- person1_dict = person1._asdict()
- print(person1_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
- # Replacing fields
- person1_updated = person1._replace(age=26)
- print(person1_updated) # Output: Person(name='Alice', age=26, city='New York')
- # Creating a namedtuple from a dictionary
- person_data = {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
- person3 = Person(**person_data)
- print(person3) # Output: Person(name='Charlie', age=35, city='Chicago')
- # Using namedtuple with default values (requires Python 3.7+)
- from collections import namedtuple
- # Define a namedtuple with default values
- PersonWithDefaults = namedtuple('PersonWithDefaults', ['name', 'age', 'city', 'email'])
- PersonWithDefaults.__new__.__defaults__ = ('unknown', 'unknown', 'unknown', 'not_provided')
- # Create instances using default values
- person4 = PersonWithDefaults(name='Daisy')
- print(person4) # Output: PersonWithDefaults(name='Daisy', age='unknown', city='unknown', email='not_provided')
- # Unpacking namedtuple
- name, age, city = person1
- print(name, age, city) # Output: Alice 25 New York
Advertisement
Add Comment
Please, Sign In to add comment