python, dictionary and int error

I have a very frustrating python problem. In this code

fixedKeyStringInAVar = "SomeKey"

def myFunc(a, b):
    global sleepTime
    global fixedKeyStringInAVar
    varMe=int("15")
    sleepTime[fixedKeyStringInAVar] = varMe*60*1000
    #more code

Now this works. BUT sometimes when I run this function I get

TypeError: 'int' object does not support item assignment

It is extremely annoying since I tried several test cases and could not reproduce the error, yet it happens very often when I run the full code. The code reads data from a db, access sites, etc. so its hard for me to go through the data since it reads from several sources and depends on 3rd party input that changes (websites).

What could this error be?


Asked by: Lydia895 | Posted: 30-11-2021






Answer 1

  1. Don't use global keyword in a function unless you'd like to change binding of a global name.

  2. Search for 'sleepTime =' in your code. You are binding an int object to the sleepTime name at some point in your program.

Answered by: Sawyer127 | Posted: 01-01-2022



Answer 2

Your sleepTime is a global variable. It could be changed to be an int at some point in your program.

The item assignment is the "foo[bar] = baz" construction in your function.

Answered by: Sam565 | Posted: 01-01-2022



Similar questions

Python dictionary error

In the below code d_arr is an array of dictionaries def process_data(d_arr): flag2 = 0 for dictionaries in d_arr: for k in dictionaries: if ( k == "*TYPE" ): """ Here we determine the type """ if (dictionaries[k].lower() == "name"): dictionaries.update({"type" : 0}) func = name(dictionaries) continue elif (dictionarie...


Key Error (0, 0) when trying to use tuple as a dictionary key in Python

I am getting the Key Error: (0, 0). In this part of my code, I am trying to create to dictionary of of block in my grid that has the key (x, y). Here's my code: self.block_list = {} for x in range(0, self.width): for y in range(0, self.height): self.block_list[(x, y)] I don't understand why (0, 0) is not being included in the dictionary.


dictionary - I'm getting Key error in python

In my python program I am getting this error: KeyError: 'variablename' From this code: path = meta_entry['path'].strip('/'), Can anyone please explain why this is happening?


Python dictionary key error

I am attempting to run a python program that can run a dictionary from a file with a list of words with each word given a score and standard deviation. My program looks like this: theFile = open('word-happiness.csv', 'r') theFile.close() def make_happiness_table(filename): ''' make_happiness_table: string -> dict creates a dictionary of happiness scores from the given file ''' return {} ...


dictionary - Key Error 4 in Python

I keep getting this error whenever I delete part of a dictionary in python. Early on I have del the_dict[1] and then later when I run through the dictionary I immediately get the error test_self = the_dict[element_x] KeyError: 4 Does anyone have any idea what that error is. Everything is properly deleted from the dictionary, but when I go back to...


python - Type Error -How should be the index in dictionary?

def __init__(self, dictionary_paths): files = [open(path, 'r') for path in dictionary_paths] dictionaries = [yaml.load(dict_file) for dict_file in files] map(lambda x: x.close(), files) self.dictionary = {} self.max_key_size = 0 for curr_dict in dictionaries: for key in curr_dict: if key in self.dictionary: self.dictionary[key].extend(curr_dict[key]) ...


Python Dictionary type error

i have a dictionary like follows: Dict = { "key1" : {"subkey1" : "value1" , "subkey2" : "value2" , "key2" : {"subkey1" : "value3" , "subkey2" : "value4 } I basically want to be able to check for values as follows if (Dict[key][any_subkey] == "value"): do something.... i am getting the TypeError: list indices must be integers, not str.......


python dictionary key error?

I am receiving this error: Traceback (most recent call last): File "/Users/Rose/Documents/workspace/METProjectFOREAL/src/test_met4.py", line 79, in <module> table_list.append(table_template % art_temp_dict) KeyError: 'artifact4' from this code: artifact_groups = grouper(4, html_list, "") for artifact_group in artifact_groups: art_temp_dict={} for a...


python - Dictionary is giving \n error, how do I get rid of the \n?

I have some code that randomly generates a word from the .txt file. I want this word to also print it's matching definition but it's not working This is what I currently have keywords = {'carrot': 'Green Vegetable.', 'apple': 'Red or Green fruit.', 'orange': 'Orange fruit.'} print ("Here is your keyword") import random with open('keywords.txt') as f: a = random.choice(l...


Key error in dictionary - python

I have two dictionaries: One is : data_obt={'Sim_1':{'sig1':[1,2,3],'sig2':[4,5,6]},'Sim_2':{'sig3':[7,8,9],'sig4':[10,11,12]},'Com_1':{'sig5':[13,14,15],'sig6':[16,17,18]},'Com_2':{'sig7':[19,20,21],'sig9':[128,23,24]}} Other one is: simdict={'sig1':'Bit 1','sig2':'Bit 2','sig3':'Bit 3','sig4':'Bit 4','sig5':'Bit 5','sig6':'Bit 6','sig7':'Bit 7','sig9':''} ...


python dictionary error when getting value from a given key

I'm starting coding in Python since yesterday and I'm going without problems. The context is a program to read an RFID card and use the readed tag to get the associated username. This will work in a embedded Linux (Debian GNU/Linux 7 (wheezy)) on a Terra board. Python version is (Python 2.7.3). I create a Dictionary an fill it with key/value pairs (both strings). When I try to get a value using one key I get an Ex...


Python dictionary ' ' key error

error showed I am running into a key error while trying to loop through a dictionary. If someone could tell me what I am doing incorrect, it would be helpful. I am trying to make a basic "Caesar cipher", a way to decode messages with an offset of 13. :) ceasar = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', '...


Python JSON dictionary key error

I'm trying to collect data from a JSON file using python. I was able to access several chunks of text but when I get to the 3rd object in the JSON file I'm getting a key error. The first three lines work fine but the last line gives me a key error. response = urllib.urlopen("http://asn.desire2learn.com/resources/D2740436.json") data = json.loads(response.read()) title = data["http://asn.desire2learn.com/re...


dictionary - Python Key Error With _

I'm getting a weird key error with Python dicts. My key is "B19013_001E" and I've named my dict "sf_tracts" with a nested dict "properties". Here is my code: x = "B19013_001E" for tract in sf_tracts: print tract["properties"][x] With this, I get a KeyError: "B19013_001E" However if I change the code to this, the values get printed: x = "B19013_001E" for tract in...


python - Having error when using list in dictionary

I declared these two dictionaries. #!/usr/bin/python switches_path = {'s1': [], 's2': [], 's3': [], 's4': []} adjs = {'s1': [s2, s4], 's2': [s1, s3], 's3': [s2, s4], 's4': [s1, s3]} I got this error: Traceback (most recent call last): File "./t.py", line 7, in <module> adjs = {'s1': [s2, s4], 's2': [s1, s3], 's3': [s2, s4], 's4': [s1, s3]} NameError: name 's2' ...


dictionary error - python

Here is my dictionary: {"draws":{"draw":[{"drawTime":"01-01-2017T22:00:00","drawNo":1771,"results":[3,3,4,9,2,9,1]}]}} I want to get the "results" from this nested dictionary but an error keeps appearing that the list indices must be integers. Basically I want to get [3,3,4,9,2,9,1]. Any help would be greatly appreciated. Here is my code: import urllib2 import js...


Trying to get max value out of a dictionary in python and getting below error

Closed. This question needs debugging detai...


Python Error while trying to read form a csv file to a dictionary

I am trying to read from a csv file to a dictionary. The problem is that I have 3 values per line (not just 2) and want to transform to a dict where the first value is the key and the last 2 values are combined to a single value (e.g. using a list or a tuple). As an example, I have the following inside csv: Calcium Enriched 100% Lactose Free Fat Free Milk,2346,57876.0 Large Organic Omega3 Brown Eggs,2568,8...


list - Error in getting item data from a Python Dictionary

I'm reading a json file, retrieved from openweathermap, to get the temperature and rain expected for a location. Here is an example of the json file I have a loop to retrieve for every index and i can get any value except rain. r...


why am i getting a key error '' in python using dictionary

i am using dijkstra's algorithm and i keep getting this error: Not Checked: ['Bank', 'Blackfriars', 'Cannon Street', 'Chancery Lane', 'Charing Cross', 'Covent Garden', 'Embankment', 'Goodge Street', 'Holborn', 'Leicester Square', 'London Bridge', 'Mansion House', 'Monument', "St Paul's", 'Temple', 'Tottenham Court Road', ''] return self.func(*args) child_cost = graph[node] KeyError: '' I...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python - Best way to create a NumPy array from a dictionary?

I'm just starting with NumPy so I may be missing some core concepts... What's the best way to create a NumPy array from a dictionary whose values are lists? Something like this: d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } Should turn into something like: data = [ [10,20,30,?,?], [50,60,?,?,?], [100,200,300,400,500] ] ...


python - List a dictionary

In a list appending is possible. But how I achieve appending in dictionary? Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | OBJECT|00000101| |.rodata Symbols from _ashldi3.o: Name Value Class ...


python - How to filter a dictionary by value?

Newbie question here, so please bear with me. Let's say I have a dictionary looking like this: a = {"2323232838": ("first/dir", "hello.txt"), "2323221383": ("second/dir", "foo.txt"), "3434221": ("first/dir", "hello.txt"), "32232334": ("first/dir", "hello.txt"), "324234324": ("third/dir", "dog.txt")} I want all values that are equal to each other to be moved into...


Python and dictionary like object

I need a python 3.1 deep update function for dictionaries (a function that will recursively update child dictionaries that are inside a parent dictionary). But I think, in the future, my function could have to deal with objects that behave like dictionaries but aren't. And furthermore I want to avoid using isinstance and type (because they are considered b...


python - Remove dictionary from list

If I have a list of dictionaries, say: [{'id': 1, 'name': 'paul'}, {'id': 2, 'name': 'john'}] and I would like to remove the dictionary with id of 2 (or name 'john'), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).


C# way to mimic Python Dictionary Syntax

Is there a good way in C# to mimic the following python syntax: mydict = {} mydict["bc"] = {} mydict["bc"]["de"] = "123"; # &lt;-- This line mydict["te"] = "5"; # &lt;-- While also allowing this line In other words, I'd like something with [] style access that can return either another dictionary or a string type, depending on how it has been set. I've been trying to work...


python - Can a dictionary be passed to django models on create?

Is it possible to do something similar to this with a list, dictionary or something else? data_dict = { 'title' : 'awesome title', 'body' : 'great body of text', } Model.objects.create(data_dict) Even better if I can extend it: Model.objects.create(data_dict, extra='hello', extra2='world')


python - Make Dictionary From 2 List

This question already has answers here:


Python dictionary simple way to add a new key value pair

Say you have, foo = 'bar' d = {'a-key':'a-value'} And you want d = {'a-key':'a-value','foo':'bar'} e = {'foo':foo} I know you can do, d['foo'] = foo #Either of the following for e e = {'foo':foo} e = dict(foo=foo) But, in all these way to add the variable foo to dict, I have had to use the word foo twice; onc...


sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}


Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: &gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.


python - How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?


python - How can I make a dictionary from separate lists of keys and values?

I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}


python - Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom)


Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?


python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...


python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python - Check if a given key already exists in a dictionary and increment it

How do I find out if a key in a dictionary has already been set to a non-None value? I want to increment the value if there's already one there, or set it to 1 otherwise: my_dict = {} if my_dict[key] is not None: my_dict[key] = 1 else: my_dict[key] += 1






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



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



top