Snippets Collections
Именованные кортежи часто используются для назначения имён полей кортежам, возвращаемым модулями csv или sqlite3:

        
EmployeeRecord = collections.namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
    print(emp.name, emp.title)
challenges_done = [('mike', 10), ('julian', 7), ('bob', 5),
                   ('mike', 11), ('julian', 8), ('bob', 6)]

challenges = defaultdict(list)
for name, challenge in challenges_done:
    challenges[name].append(challenge)

challenges
User = namedtuple('User', 'name role sur')
user = User(name='bob', role='coder', sur='ellepola')
User = namedtuple('User', 'name role sur')
user = User(name='bob', role='coder', sur='ellepola')
star

Sun Mar 05 2023 00:07:03 GMT+0000 (Coordinated Universal Time) https://proglib.io/p/ne-izobretat-velosiped-ili-obzor-modulya-collections-v-python-2019-12-15

#sqlite3 #collections #namedtuple
star

Wed May 26 2021 17:59:37 GMT+0000 (Coordinated Universal Time)

#python #namedtuple
star

Wed May 26 2021 17:51:42 GMT+0000 (Coordinated Universal Time)

#python #namedtuple
star

Wed May 26 2021 17:51:37 GMT+0000 (Coordinated Universal Time)

#python #namedtuple

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension