How to maintain lists and dictionaries between function calls in Python?

I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls

Suppose the dic is :

a = {'a':1,'b':2,'c':3}

At first call,say,I changed a[a] to 100 Dict becomes a = {'a':100,'b':2,'c':3}

At another call,i changed a[b] to 200 I want that dic to be a = {'a':100,'b':200,'c':3}

But in my code a[a] doesn't remain 100.It changes to initial value 1.

I need an answer ASAP....I m already late...Please help me friends...


Asked by: Miller461 | Posted: 28-01-2022






Answer 1

You might be talking about a callable object.

class MyFunction( object ):
    def __init__( self ):
        self.rememberThis= dict()
    def __call__( self, arg1, arg2 ):
        # do something
        rememberThis['a'] = arg1
        return someValue

myFunction= MyFunction()

From then on, use myFunction as a simple function. You can access the rememberThis dictionary using myFunction.rememberThis.

Answered by: Lana147 | Posted: 01-03-2022



Answer 2

You could use a static variable:

def foo(k, v):
  foo.a[k] = v
foo.a = {'a': 1, 'b': 2, 'c': 3}

foo('a', 100)
foo('b', 200)

print foo.a

Answered by: David275 | Posted: 01-03-2022



Answer 3

Rather than forcing globals on the code base (that can be the decision of the caller) I prefer the idea of keeping the state related to an instance of the function. A class is good for this but doesn't communicate well what you are trying to accomplish and can be a bit verbose. Taking advantage of closures is, in my opinion, a lot cleaner.

def function_the_world_sees():
    a = {'a':1,'b':2,'c':3}

    def actual_function(arg0, arg1):
        a[arg0] = arg1
        return a

    return actual_function
stateful_function = function_the_world_sees()

stateful_function("b", 100)    
stateful_function("b", 200)

The main caution to keep in mind is that when you make assignments in "actual_function", they occur within "actual_function". This means you can't reassign a to a different variable. The work arounds I use are to put all of my variables I plan to reassign into either into a single element list per variable or a dictionary.

Answered by: Kate955 | Posted: 01-03-2022



Answer 4

If 'a' is being created inside the function. It is going out of scope. Simply create it outside the function(and before the function is called). By doing this the list/hash will not be deleted after the program leaves the function.

a = {'a':1,'b':2,'c':3}

# call you funciton here

Answered by: Lana273 | Posted: 01-03-2022



Answer 5

You can 'cheat' using Python's behavior for default arguments. Default arguments are only evaluated once; they get reused for every call of the function.

>>> def testFunction(persistent_dict={'a': 0}):
...     persistent_dict['a'] += 1
...     print persistent_dict['a']
...
>>> testFunction()
1
>>> testFunction()
2

This isn't the most elegant solution; if someone calls the function and passes in a parameter it will override the default, which probably isn't what you want.

If you just want a quick and dirty way to get the results, that will work. If you're doing something more complicated it might be better to factor it out into a class like S. Lott mentioned.

EDIT: Renamed the dictionary so it wouldn't hide the builtin dict as per the comment below.

Answered by: Vanessa167 | Posted: 01-03-2022



Answer 6

This question doesn't have an elegant answer, in my opinion. The options are callable objects, default values, and attribute hacks. Callable objects are the right answer, but they bring in a lot of structure for what would be a single "static" declaration in another language. Default values are a minor change to the code, but it's kludgy and can be confusing to a new python programmer looking at your code. I don't like them because their existence isn't hidden from anyone who might be looking at your API.

I generally go with an attribute hack. My preferred method is:

def myfunct():
    if not hasattr(myfunct, 'state'): myfunct.state = list()
    # access myfunct.state in the body however you want

This keeps the declaration of the state in the first line of the function where it belongs, as well as keeping myfunct as a function. The downside is you do the attribute check every time you call the function. This is almost certainly not going to be a bottleneck in most code.

Answered by: Caroline284 | Posted: 01-03-2022



Answer 7

Personally, I like the idea of the global statement. It doesn't introduce a global variable but states that a local identifier actually refers to one in the global namespace.

d = dict()
l = list()
def foo(bar, baz):
    global d
    global l
    l.append(bar, baz)
    d[bar] = baz

In python 3.0 there is also a "nonlocal" statement.

Answered by: Emma219 | Posted: 01-03-2022



Similar questions

variables - python: dictionaries of lists are somehow coupled

I wrote a small python program to iterate over data file (input_file) and perform calculations. If calculation result reaches certain states (stateA or stateB), information (hits) are extracted from the results. The hits to extract depend on parameters from three parameter sets. I used a dictionary of dictionaries to store my parameter sets (param_sets) and a dictionary of l...


python - Add different variables in two dictionaries

I need a little bit of help here. I am a new python coder. I need a lot of help. So, I want to add the different variables in two dictionaries. An example is: x = {'a':1, 'b':2} y = {'b':1, 'c':2} I want to replace these values such that it looks like: x = {'a':1, 'b':2, 'c':0} y = {'a':0, 'b':1, 'c':2} The order of variables has to be same. Please help...


Using Nested Dictionaries in Python -- combining two datasets with a common 'key' and different other variables

I have two csv datasets with county level data. Each dataset identifies the county by a FIPS code. I want to create a nested 'master' dictionary such that I can call it with an identifying FIPS code and it will return the corresonding 'inner' dictionary for that FIPS, which contains all the information from both datasets. I understand the general way to set up nested dictionaries, namely: >>...


python - Create Variables and Dictionaries from .txt

I currently have this as my code. def makeFolder(): if not os.path.exists('Game Saves'): os.makedirs('Game Saves') def saveAllPlayerInfo(dest,fileName): f=open(dest+fileName,'w') f.write("{0}:{1}\n".format('playerName',playerName)) f.write("playerStats={\n") f.write("\t'{0}':'{1}'\n".format('playerMaxHp',playerStats['playerMaxHp'])) f.write("\t'{0}':'{1}'\n".format('playerCurren...


Python - Create names for dictionaries using variables from list

I am trying to calculate the standings for a sports league. Tie breakers are based on head 2 head records. So in order to determine the team higher in the standings when a tie in points occurs I need to be able to pull head to head records between teams from a dictionary. My plan was to create a dictionary for every team containing all their head 2 head records against other teams. The problem is, the team ...


python - How to use dictionaries with variables

I'm trying to create a python program to automatically sort jobs that I'm working on. So far I have managed to create a dictionary. For example: monday = ('1' : 'clean the counters') and assign everyone a number: joe = random.randint(1,3) but when I try: print ("Today Joe has to do the", monday[joe]") it spits out the err...


python - Creating new dictionaries as variables in a list

I'm working on a program for a class project that takes user input and creates a new dictionary that is then added to a list. I'm stuck on how to create new dictionary names for each entry and figured using variables to alter the name would be a good answer to the problem (I.E. dictx where x is the entry index) however, researching this solution has shown me that creating variable names using variables is considered a bad ...


variables in dictionaries in python

I am trying to create a DataFrame using a Dictionary in which I have added variables as values.. gpa_min = df_gpa.min() gpa_Q1 = df_gpa.quantile(0.25) ratio_gpa = 'gpa ratio Q1/outlier is ', df_gpa.quantile(0.25)/df_gpa.min(), 'should be' gre_min = df_gre.min() gre_Q1 = df_gre.quantile(0.25) ratio_gre = 'gre ratio Q1/outlier is ', df_gre.quantile(0.25)/df_gre.min() index = ['gre','gpa'] columns = ['min...


python - Cannot find variables in a list of dictionaries

I am trying to ge around with APIs in general. To test this I coded this little snippet of code to get a list of all the channels on the Swedish national public service radio, and I want to print the ID and NAME of the channels: import requests as rq import json from pprint import pprint resp = rq.get('http://api.sr.se/api/v2/channels? format=json&indent=TRUE') respjson = json.loads(resp.text) pp...


python - How to read a csv file for variables and dictionaries from different columns?

So I have a CSV file with 2 columns one of the columns being the dictionary key (All the values for the keys are 1) and a column for time which is only in one cell as its the final time. I have found a code that works but it seems a bit excessive and was wondering if anyone knows of any way of shortening it down? with open('coors.csv', mode='r') as infile: reader = csv.reader(infile) next(reader, No...


data mining - Comparing multiple dictionaries in Python

I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns. When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionari...


dictionary - Comparing dictionaries in Python

Given two dictionaries, d1 and d2, and an integer l, I want to find all keys k in d1 such that either d2[k]<l or k not in l. I want to output the keys and the corresponding values in d2, except if d2 does not contain the key, I want to print 0. For instance, if d1 is a: 1 b: ...


python - Map two lists into one single list of dictionaries

Imagine I have these python lists: keys = ['name', 'age'] values = ['Monty', 42, 'Matt', 28, 'Frank', 33] Is there a direct or at least a simple way to produce the following list of dictionaries ? [ {'name': 'Monty', 'age': 42}, {'name': 'Matt', 'age': 28}, {'name': 'Frank', 'age': 33} ]


python - Can I get rows from SQLAlchemy that are plain arrays, rather than dictionaries?

I'm trying to optimize some Python code. The profiler tells me that SQLAlchemy's _get_col() is what's killing performance. The code looks something like this: lots_of_rows = get_lots_of_rows() for row in lots_of_rows: if row.x == row.y: print row.z I was about to go through the code and make it more like this... lots_of_rows = get_lots_of_rows() for row in lots_...


python - Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?

I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically: I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So: >>> type(myDict) <type 'dict'> >>> type(myDict[u'myKey']) <type 'dict'> >>> type(myDict[u'myKey'][u'myKey2']) <type 'list'> >>> ty...


python - Creating dictionaries with pre-defined keys

In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?


Dictionaries with volatile values in Python unit tests?

I need to write a unit test for a function that returns a dictionary. One of the values in this dictionary is datetime.datetime.now() which of course changes with every test run. I want to ignore that key completely in my assert. Right now I have a dictionary comparison function but I really want to use assertEqual like this: def my_func(self): return {'monkey_head_count': 3, 'monke...


dictionary - "Adding" Dictionaries in Python?

This question already has answers here:


python - Sorting a list of dictionaries of objects by dictionary values

This is related to the various other questions about sorting values of dictionaries that I have read here, but I have not found the answer. I'm a newbie and maybe I just didn't see the answer as it concerns my problem. I have this function, which I'm using as a Django custom filter to sort results from a list of dictionaries. Actually, the main part of this function was answered in a related question on stackoverfl...


dictionary - item frequency in a python list of dictionaries

Ok, so I have a list of dicts: [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] and I want the 'frequency' of the items within each column. So for this I'd get something like:...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top