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

15 30 50 per page
1
2 3 4 5
19