nathanwailes

Namedtuple

Jun 9th, 2024
464
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. """
  2. """
  3. from collections import namedtuple
  4.  
  5. # Defining a namedtuple
  6. Person = namedtuple('Person', ['name', 'age', 'city'])
  7.  
  8. # Creating instances of namedtuple
  9. person1 = Person(name='Alice', age=25, city='New York')
  10. person2 = Person(name='Bob', age=30, city='Los Angeles')
  11.  
  12. # Accessing fields
  13. print(person1.name)   # Output: Alice
  14. print(person1.age)    # Output: 25
  15. print(person1.city)   # Output: New York
  16.  
  17. # Accessing fields by index
  18. print(person2[0])     # Output: Bob
  19. print(person2[1])     # Output: 30
  20. print(person2[2])     # Output: Los Angeles
  21.  
  22. # Accessing fields using _fields attribute
  23. print(person1._fields)  # Output: ('name', 'age', 'city')
  24.  
  25. # Converting namedtuple to a dictionary
  26. person1_dict = person1._asdict()
  27. print(person1_dict)  # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
  28.  
  29. # Replacing fields
  30. person1_updated = person1._replace(age=26)
  31. print(person1_updated)  # Output: Person(name='Alice', age=26, city='New York')
  32.  
  33. # Creating a namedtuple from a dictionary
  34. person_data = {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
  35. person3 = Person(**person_data)
  36. print(person3)  # Output: Person(name='Charlie', age=35, city='Chicago')
  37.  
  38. # Using namedtuple with default values (requires Python 3.7+)
  39. from collections import namedtuple
  40.  
  41. # Define a namedtuple with default values
  42. PersonWithDefaults = namedtuple('PersonWithDefaults', ['name', 'age', 'city', 'email'])
  43. PersonWithDefaults.__new__.__defaults__ = ('unknown', 'unknown', 'unknown', 'not_provided')
  44.  
  45. # Create instances using default values
  46. person4 = PersonWithDefaults(name='Daisy')
  47. print(person4)  # Output: PersonWithDefaults(name='Daisy', age='unknown', city='unknown', email='not_provided')
  48.  
  49. # Unpacking namedtuple
  50. name, age, city = person1
  51. print(name, age, city)  # Output: Alice 25 New York
  52.  
Advertisement
Add Comment
Please, Sign In to add comment