namedtuple

Convert a namedtuple into a dictionary

Convert a namedtuple into a dictionary Question: I have a named tuple class in python class Town(collections.namedtuple(‘Town’, [ ‘name’, ‘population’, ‘coordinates’, ‘population’, ‘capital’, ‘state_bird’])): # … I’d like to convert Town instances into dictionaries. I don’t want it to be rigidly tied to the names or number of the fields in a Town. Is there …

Total answers: 6

How to cast tuple into namedtuple?

How to cast tuple into namedtuple? Question: I’d like to use namedtuples internally, but I want to preserve compatibility with users that feed me ordinary tuples. from collections import namedtuple tuple_pi = (1, 3.14, "pi") #Normal tuple Record = namedtuple("Record", ["ID", "Value", "Name"]) named_e = Record(2, 2.79, "e") #Named tuple named_pi = Record(tuple_pi) #Error TypeError: …

Total answers: 1

Relevance of typename in namedtuple

Relevance of typename in namedtuple Question: from collections import namedtuple Point = namedtuple(‘whatsmypurpose’,[‘x’,’y’]) p = Point(11,22) print(p) Output: whatsmypurpose(x=11,y=22) What’s the relevance/use of ‘whatsmypurpose’? Asked By: Phoenix || Source Answers: namedtuple() is a factory function for tuple subclasses. Here, ‘whatsmypurpose’is the type name. When you create a named tuple, a class with this name (whatsmypurpose) …

Total answers: 3

What does *tuple and **dict mean in Python?

What does *tuple and **dict mean in Python? Question: As mentioned in PythonCookbook, * can be added before a tuple. What does * mean here? Chapter 1.18. Mapping Names to Sequence Elements: from collections import namedtuple Stock = namedtuple(‘Stock’, [‘name’, ‘shares’, ‘price’]) s = Stock(*rec) # here rec is an ordinary tuple, for example: rec …

Total answers: 1

Can't set attribute for subclasses of namedtuple

Can't set attribute for subclasses of namedtuple Question: It looks like this or this are somewhat related threads, but still haven’t figured things out 🙂 I’m trying to create a subclass of namedtuple and provide different initializers so that I can construct objects in different ways. For example: >>> from collections import namedtuple >>> class …

Total answers: 5

How do I create pandas DataFrame (with index or multiindex) from list of namedtuple instances?

How do I create pandas DataFrame (with index or multiindex) from list of namedtuple instances? Question: Simple example: from collections import namedtuple import pandas Price = namedtuple(‘Price’, ‘ticker date price’) a = Price(‘GE’, ‘2010-01-01’, 30.00) b = Price(‘GE’, ‘2010-01-02′, 31.00) l = [a, b] df = pandas.DataFrame.from_records(l, index=’ticker’) Traceback (most recent call last) … KeyError: …

Total answers: 2

How to pickle a namedtuple instance correctly

How to pickle a namedtuple instance correctly Question: I’m learning how to use pickle. I’ve created a namedtuple object, appended it to a list, and tried to pickle that list. However, I get the following error: pickle.PicklingError: Can’t pickle <class ‘__main__.P’>: it’s not found as __main__.P I found that if I ran the code without …

Total answers: 5

Pythonic way to sorting list of namedtuples by field name

Pythonic way to sorting list of namedtuples by field name Question: I want to sort a list of named tuples without having to remember the index of the fieldname. My solution seems rather awkward and was hoping someone would have a more elegant solution. from operator import itemgetter from collections import namedtuple Person = namedtuple(‘Person’, …

Total answers: 5

Named tuple and default values for optional keyword arguments

Named tuple and default values for optional keyword arguments Question: I’m trying to convert a longish hollow “data” class into a named tuple. My class currently looks like this: class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right After conversion to namedtuple it looks like: from collections import …

Total answers: 23

What is the pythonic way to read CSV file data as rows of namedtuples?

What is the pythonic way to read CSV file data as rows of namedtuples? Question: What is the best way to take a data file that contains a header row and read this row into a named tuple so that the data rows can be accessed by header name? I was attempting something like this: …

Total answers: 3