Skip to main content

Questions tagged [namedtuple]

namedtuple is a data structure provided by the Python collections module. It enables the creation of tuples with named elements (e.g., a Student tuple with the values (name, school, age) rather than a tuple with just two strings and an integer).

namedtuple
1 vote
0 answers
36 views

Setting the return type of a custom namedtuple

I have a sample_config.json file with potentially an arbitrary number of the parameters. An example of the sample_config.json is as follows: { "tableA_ID": "tableA.csv", "...
user4687531's user avatar
  • 1,101
1 vote
1 answer
35 views

Why pyomo unpack namedtuples in constraints?

I am new to pyomo and I want to understand why it works with namedtuple the way it works. There is a code sample: from collections import namedtuple import pyomo.environ as pyo Product = namedtuple(&...
Alexey's user avatar
  • 99
0 votes
1 answer
20 views

Dict comprehension over multiple dicts with missing keys

I have a piece of legacy python2 code that looks like the following # dict1 and dict2 are inputs. dict2 is where the value is a 4-tuple return { key: [ NamedTuple1(val1, ...
roulette01's user avatar
  • 2,344
1 vote
1 answer
37 views

How can I access the name of namedtuple attribute from inside a method if it wasn't passed as a string?

This is a followup to How can I pass a namedtuple attribute to a method without using a string?. Given this solution to the above: from typing import NamedTuple class Record(NamedTuple): id: int ...
MikeP's user avatar
  • 323
0 votes
1 answer
71 views

Trying to understand behavior of `_field_defaults` of `namedtuple` in Python 3.9 [closed]

I am new to Python's namedtuple, particularly, _field_defaults. According to Python 3.12.3 official doc, some namedtuple._field_defaults Dictionary mapping field names to default values. Would ...
Ku Zijie's user avatar
  • 473
-1 votes
1 answer
55 views

Get the total count of 1 field of a list of namedtuple objects

In Python, what is the easiest way to get the total count of one field from a set of named tuples? In this example, I'm looking for the total count of TestResults.failed, which should be 4. It's ...
David Gard's user avatar
  • 11.8k
0 votes
2 answers
52 views

Conversion of Dataframe to namedtuple of numpy arrays

I need to convert my pandas dataframe to tuple of numpy arrays. My code is like, import pandas as pd data = {'Class':[10., 11., 9., 8.], 'Age':[27., 24., 22., 32.], 'Mark':[76., 56., ...
Aristocrat's user avatar
0 votes
1 answer
126 views

_pickle.PicklingError: Can't pickle <class '__main___.{CONST} '>: attribute lookupfaileddir_namesmain_on __main__ failed

firstly dir_names works well when pickling dir_names = collections.namedtuple('dir_names', ['mark', 'category']) pickle.dump(dir_names, open('tmp.bin', 'wb')) I want make dir_name a const DIR_NAMES = ...
king Carrey's user avatar
0 votes
1 answer
54 views

define the args of a function outside the actual call

I have a function that has to call other functions, with a not-fixed number and type of arguments, that I want to set in a dictionary. Something like this: def main_function(...
invalid syntax's user avatar
0 votes
1 answer
78 views

How is Python able to distinct type names of namedtuples? [duplicate]

My model class has to provide lots of queries and I would like to return query results as namedtuple. My solution is working, but I don't know why :) - so I would like to get some clarification ...
Markus's user avatar
  • 11
1 vote
0 answers
27 views

Is it Possible to extract the name of an Argument in TypeScript? [duplicate]

Using Parameters I can get the argument types, even as named tuple, but how can I access the name of the argument (or the tuple for that matter), is it possible in the latest TypeScript Version (5.1.6)...
dsalex1's user avatar
  • 454
0 votes
1 answer
83 views

Why does namedtuple + namedtuple return a regular tuple?

from collections import namedtuple foo_a = namedtuple("foo_a", ["a1", "a2", "a3"]) foo_b = namedtuple("foo_b", ["b1", "b2", "...
sbwcwso's user avatar
  • 15
2 votes
1 answer
350 views

Using a cached property on a named tuple

from typing import NamedTuple from functools import cached_property class Rectangle(NamedTuple): x: int y: int @cached_property def area(self): return self.x * self.y I ...
COVFEFE-19's user avatar
0 votes
1 answer
129 views

Print named tuple value in a list

A function is returning me the below list of named tuples: [popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768), popenfile(path='/var/log/monit.log', fd=4, position=...
Saga Harby's user avatar
1 vote
1 answer
33 views

Is it be possible to give custom names to the newly created type that is pushed to the end of a tuple type, without affecting other argument names?

Here i have a type that takes a tuple type with a fixed number of parameters, and also includes an array of strings as the final parameter. I want to give the tuple type parameters custom names a, b ...
cyrus-d's user avatar
  • 815
0 votes
1 answer
62 views

modifiy one element of namedtuple of list

I have written script to extract some information from pdf file. Each page is read as blocks. if [V2G has been found, then it will saved it as well as the title ,subtitle and the bulleted list. My ...
user34088's user avatar
0 votes
1 answer
37 views

How can I make a data structure containing a variable so that it updates when the variable is re-defined?

I am making a text adventure game. I'm using a named tuple to define locations. Location = namedtuple('Location', ['desc', 'ldesc', 'func', 'dirloc']) entrance = foyer = None entrance = Location('...
Odoul's user avatar
  • 23
2 votes
1 answer
329 views

How to alias class attributes when creating NamedTuple?

I want to alias project_version with init_version, but since NamedTuple is a factory method I'm having difficulty in doing this. from typing import NamedTuple class ProjectMetadata(NamedTuple): &...
Blueynuey's user avatar
1 vote
1 answer
506 views

PyCharm: namedtuple: unexpected argument, unfilled parameter

In PyCharm, you can declare a named tuple. from collections import namedtuple InstTyp = namedtuple( typename='InstTyp', field_names=''' instance_type memory num_cpus ...
Brian Fitzgerald's user avatar
-1 votes
1 answer
34 views

How to type a returned Array inside an Array? [closed]

return [[x, y], d, prevRing, prevRingPosition] That is my return statement and I want to make a type for its function type nextUlamReturn = [ number[], d: number, prevRing: number, ...
Felix Prackwieser's user avatar
1 vote
1 answer
225 views

NamedTuple - сhecking types of fields at runtime

Is there a neat solution to raise an error if a value is passed to the NamedTuple field that does not match the declared type? In this example, I intentionally passed page_count str instead of int. ...
JobWeek's user avatar
  • 19
3 votes
1 answer
415 views

Why does mypy fail to detect that a raw tuple value is a NamedTuple?

I have this piece of code: from typing import NamedTuple class KeyTuple(NamedTuple): key: str storage: dict[KeyTuple, int] = {} storage.get(("kek",)) that raises an error: test_mypy....
Leydenberg's user avatar
1 vote
1 answer
131 views

Difference between a class(namedtuple) and a namedtuple

What is the difference between class(namedtuple) and only namedtuple, they look different but in both cases sensor seems to be the same thing, and what kind of functionality can be added inside class ...
Tung's user avatar
  • 33
-1 votes
1 answer
462 views

How to find delete a student record in Python (example on a Students Mark exercise)

Start a new Python script and write some suitable input commands to store three items of data into three variables: Student Name, Coursework Mark, and Exam Mark. The inputs for coursework mark and ...
tab's user avatar
  • 15
2 votes
0 answers
46 views

Any dict-like mappable objects in Python that only show preview of contents when __repr__?

I'm looking for an object I can use to store largish dataframes and sklearn objects. Ideally I would like to store them as pd.Series because it has the behavior I'm looking for in that I can do the ...
O.rka's user avatar
  • 30.5k
0 votes
2 answers
99 views

NamedTuple is shared across variables

from typing import NamedTuple, List, Set, Tuple, Dict class EmbeddingInfoStruct(NamedTuple): emb_names : list[str] =[] idx_in_data: list[int] =[] emb_dim: list[int] =[] info1 =...
imachabeli's user avatar
0 votes
1 answer
48 views

Python data json dictionary

I wanted to read tar.json file, so I write: import json with open('tar.json', "r", encoding='utf-8') as read_file: data = json.load(read_file) and print it as dictionary, for ...
Malum Phobos's user avatar
0 votes
1 answer
2k views

How to access name of named tuple in Typescript

I want to access the name from a named tuple to use within one of my functions. Is there a way to access the name only, similar to how you can access the type only by using the index of the tuple ...
sayandcode's user avatar
  • 2,775
0 votes
0 answers
36 views

Dynamically extend `__del__` cleanup code on an instance

I want to bind a dynamically created namedtuple to a class When an instance of the class is initialized, a new namedtuple-type is created, and registered in globals() (this allows pickling). When ...
Hyperplane's user avatar
  • 1,644
0 votes
1 answer
286 views

Use Tuple values in Object initalizer syntax

I'm trying to initialize properties of an object I am creating with the values of a named tuple. Something like this public Person DoIt() { return new Person { (First, Last) = GetFirstAndLast(id)...
comecme's user avatar
  • 6,286
0 votes
0 answers
79 views

How to check type of namedtuple defined within a different scope

If a namedtuple is defined within a function, is it possible to use isinstance() to check the type of the namedtuple outside of the function. I'm surprised that I'm able to use type() to get the type, ...
dewser_the_board's user avatar
5 votes
1 answer
914 views

Why can we inherit `typing.NamedTuple`?

After Python 3.6, we have typing.NamedTuple, which is a typed version of collections.namedtuple(), we can inherit it like a class: class Employee(NamedTuple): name: str id: int Compared with ...
Mechanic Pig's user avatar
  • 7,716
1 vote
3 answers
449 views

How to add a list of field names to a class based on NamedTuple?

I have a basic class like this: from typing import NamedTuple class A(NamedTuple): f1: str = "" aa = A("haha") print(aa) Now suppose I have a list of more fields that I want ...
user3768495's user avatar
  • 4,447
0 votes
0 answers
386 views

types.GenericAlias - subscriptable Types and their use

I was working with namedtuples and learned something that I found odd at first. Still not quite sure how or why this works and what can be the use of this: from collections import namedtuple Card = ...
pangna's user avatar
  • 61
1 vote
3 answers
203 views

Python namedtuples elementwise addition

Is there a more pythonic way to implement elementwise addition for named tuples? Using this class that inherits from a namedtuple generated class named "Point I can do elementwise addition for ...
Isaacnfairplay's user avatar
2 votes
0 answers
42 views

Concise creation of an object with an attribute in Python

I want to pass an object with attribute key set to 42 to function f. This will be done only once, and the object and its type is discarded. Here is my solution: from collections import namedtuple def ...
Paul Jurczak's user avatar
  • 7,802
0 votes
0 answers
20 views

Python serialize namedtuple key in dictionary to json [duplicate]

FB = namedtuple(“FB”, (“foo”,”bar”)) fb = FB(123, 456) test_dict={fb:999} How to serialize to json for test_dict?
ideate's user avatar
  • 1
1 vote
1 answer
803 views

Python namedtuple: AttributeError: 'tuple' object has no attribute 'end_pos'

I have a class that starts as follows: from collections import namedtuple class Parser: Rule = namedtuple('Rule', ['lhs', 'rhs', 'dot_pos', 'start_pos', 'end_pos']) # __init__ ... Since ...
TiMauzi's user avatar
  • 236
0 votes
2 answers
164 views

Getting error when trying to create namedtuple object using _make function

Hi all I recently started learning Python collections module. When I was trying to implement namedtuple collections for practice I got an error. I tried searching for in the official Python ...
Vishal Lade's user avatar
0 votes
0 answers
22 views

Why is namedtuple rename=True renaming an "_z" field [duplicate]

So "_z" is not a keyword, and is a value identifier. print("_z".isidentifier()) returns True import keyword print(keyword.iskeyword("_z")) returns False So why is named ...
smackenzie's user avatar
  • 2,982
4 votes
2 answers
318 views

Map a function to all a typing.NamedTuple fields and get one back?

Is there a way to apply a function to all entries of a NamedTuple and get an object of the same type back? The following code from typing import NamedTuple class MyNamedTuple(NamedTuple): a: int ...
fuenfundachtzig's user avatar
2 votes
2 answers
215 views

Not able to add value to List of named tuple

I have a named List of named tuple and from this function OnEndCircularReferencesCalculation() I am trying to add value to named tuple but getting error message like : 'Index was out of range. Must be ...
Ramesh Dutta's user avatar
0 votes
1 answer
54 views

Storing value for a point using named tuple?

I am trying to design a spreadsheet app. I have been able to come up with a class for my Index which is typically the point consisting of row, col. I want to be able to assign a value to the point. ...
SDRJ's user avatar
  • 540
4 votes
1 answer
2k views

Apache Beam infer schema using NamedTuple (Python)

I am quite new to apache beam and I am wondering how to infer schema to a pcollection using namedtuple. The example from the documentation Programming Guide states: class Transaction(typing.NamedTuple)...
Sephixx's user avatar
  • 157
-2 votes
1 answer
197 views

Write a new CSV File from Existing CSV File with many Conditions

I want to write a CSV File which gets Data from and depending from an existing CSV File. Existing_FILE: Date, Value, Name, sh 2022-01-15, 30,00, Monthly1 - #1500, H 2022-01-18, 130,00, Monthly50, S ...
RichardeRicharde's user avatar
1 vote
0 answers
83 views

Searching a List of NamedTuples for Specific Attribute [duplicate]

I have a list of NamedTuples (extract below) and I want to search through the list and print "Found" if an attribute of one of the tuples contains a specific string. This is my first time ...
Andy's user avatar
  • 521
2 votes
0 answers
286 views

how to model simple nested data static structure instead of nested dictionaries (namedtuple, dataclass... )

I hope there is some best practice or design pattern for use case of having simple nested data/mapping with need to pre-store data, select proper data group, and conveniently access specific values. ...
stam's user avatar
  • 330
5 votes
1 answer
5k views

Can I unpack/destructure a typing.NamedTuple?

This is a simple question so I'm surprised that I can't find it asked on SO (apologies if I've missed it), and it always pops into my mind as I contemplate a refactor to replace a tuple by a ...
Cai's user avatar
  • 1,929
0 votes
2 answers
234 views

Are pickle-able tuple-factories (with names) possible?

There are several questions about pickling namedtuples already, however none of the ones I found [1] [2] [3] [4] deals with the case of pickling a namedtuple that is bound on an object instance. ...
Hyperplane's user avatar
  • 1,644
0 votes
1 answer
231 views

Mypy does not detect errors regarding the use of NamedTuple inside functions

In the following code the defintions of x2 and x3 are obviously wrong, yet mypy does not complain. from typing import NamedTuple class X(NamedTuple): a: float b: float c: float def foo():...
Friedrich Gretz's user avatar

15 30 50 per page
1
2 3 4 5
11