Python AttributeError: 'dict' object has no attribute 'append' - python

I am creating a loop in order to append continuously values from user input to a dictionary but i am getting this error:
AttributeError: 'dict' object has no attribute 'append'
This is my code so far:
for index, elem in enumerate(main_feeds):
print(index,":",elem)
temp_list = index,":",elem
li = {}
print_user_areas(li)
while True:
n = (input('\nGive number: '))
if n == "":
break
else:
if n.isdigit():
n=int(n)
print('\n')
print (main_feeds[n])
temp = main_feeds[n]
for item in user:
user['areas'].append[temp]
Any ideas?

Like the error message suggests, dictionaries in Python do not provide an append operation.
You can instead just assign new values to their respective keys in a dictionary.
mydict = {}
mydict['item'] = input_value
If you're wanting to append values as they're entered you could instead use a list.
mylist = []
mylist.append(input_value)
Your line user['areas'].append[temp] looks like it is attempting to access a dictionary at the value of key 'areas', if you instead use a list you should be able to perform an append operation.
Using a list instead:
user['areas'] = []
On that note, you might want to check out the possibility of using a defaultdict(list) for your problem. See here

As the error suggests, append is not a method or attribute, meaning you cannot call append in the dictionary user.
Instead of
user['areas'].append[temp]
Use
user['areas'].update[temp]

Either
use dict.setdefault() if the key is not added yet to dictionary :
dict.setdefault(key,[]).append(value)
or use, if you already have the keys set up:
dict[key].append(value)
source: stackoverflow answers

Related

How to get all the iterations in a list with none values included from a tweet?

I have set of tweets with 10 dictionaries in the list "tweets". Each dictionary has several tweets. The first tweet has 100 and the rest 9 have 15 each.
I need the location of each tweet in all the dictionaries.
When I try to iterate the values from a list it shows this error.
if (type(tweets[j]['statuses'][k]['place']['name'])) != None:
TypeError: 'NoneType' object is not subscriptable
The code I have used for the iteration is
for j in range (0,10):
while j == 0:
for k in range(0,100):
st1 = tweets[j]['statuses'][k]['place']['name']
print(st1)
I tried using "filter" to take out the "None" values, even that is not working.
not every tweet has a location tagged to it. so it has None values. I need to print the locations of the tweets that are tagged.
Have you tried to check if the 'place' key is first available. I can see from your code that you are checking for ['place']['name']
Can you test your logic with the following filter logic without ['name']:
...
if (isinstance(tweets[j].get('statuses',[])[k].get('place', {}))) == dict:
...
The twitter api returns json, which is a dictionary type in Python. When you are calling keys using dict[key] syntax, this is called subscripting. Now, nested calls on a dict object are dependent on that object being a dictionary type:
dict[a][b] relies on dict[a] being a dictionary with key b being available. If dict[a] is a different type, say None or int, it is not subscriptable. This means that there is not necessarily a get attribute for that type. A simple way to fix this would be the following:
check = tweets[j]['statuses'][k]['place']
if isinstance(check, dict):
# do things
This makes sure that check is of type dict and therefore can be subscripted with a key
EDIT: Note that using dict[key] syntax is not safe against KeyErrors. If you want to avoid those, use get:
my_dictionary = {'a': 1, 'b': 2}
my_dictionary['c'] # Raises KeyError: 'c' not in dictionary
my_dictionary.get('c') # returns None, no KeyError
It takes the form dict.get(key, <return_value>), where return_value defaults to None
To make your program a bit more readable and avoid the inevitable infinite loop, ditch the while loop:
# This will get individual tweets
for tweet in tweets:
# Returns all statuses or empty list
statuses = tweet.get('statuses', [])
for status in statuses:
if not isinstance(status, dict):
continue # will jump to next iteration of inner for loop
# Will be a name or None, if empty dict is returned from place
name = status.get('place', {}).get('name')
if name:
print(name)
for element in tweets:
for s in element.get('statuses'):
place = s.get('place')
print(place['name'])
This fixed it.

Create variable number of dictionary with name taken from list in Python

I have a list which grows and shrinks in a for loop. The list looks like following :- . With every element inside list of list i want to associate it to a separate dictionary.
list123 = [[1010,0101],[0111,1000]]
In this case I want to create 4 dictionary with the following name
dict1010 = {}
dict0101 = {}
dict0111 = {}
dict1000 = {}
I tried following loop
for list1 in list123:
for element in list1:
dict + str(element) = dict()
This is the error i am getting
SyntaxError: can't assign to literal
while you can dynamically create variables, unless there is an overwhelming need to do that use instead a dictionary of dictionary witch key is the name you want, like this
my_dicts=dict()
for list1 in list123:
for element in list1:
my_dicts["dict" + str(element)] = dict()
and to access one of them do for example my_dicts["dict1010"]
You can uses globals() function to add names to global namespace like this
for list1 in list123:
for element in list1:
globals()["dict"+str(element)] = {}
this will add variables with the names you want as if you created them using dictx={} also numbers that begins with 0 won't convert well using str() so you should make your list a list of strings
First of all, I must say that you shouldn't do this. However, if you really want to, you can use exec.
If you really want to do this, you could use exec:
list123 = [[1010,0101],[0111,1000]]
for list1 in list123:
for element in list1:
var = 'dict' + str(element)
exec(var + ' = dict()')

TypeError: list indices must be integers, not str - loading strings from a list

So I have a list of strings I want to make = 999
with open ("Inventory.txt", 'r') as i:
for items in i:
item = GetItemID(items)
PositionOfItems[items]=HERO_INVENTORY_POS
HERO_INVENTORY_POS is = 999, but I get the error displayed above, if I'm missing anything else require please tell me.
This is the code I used for spawning an item so I kinda just tried to recreate that.`
ItemRequest = input("Which item would you like?").upper()
for i in ItemList:
if i == ItemRequest:
ItemRequest = GetItemID(ItemRequest)
PositionOfItems[ItemRequest]=HERO_INVENTORY_POS`
If PositionOfItems is a list, then items needs to be in an integer. Right now, it's a string, because you're reading it from a file.
Try:
PositionOfItems[int(items)]=HERO_INVENTORY_POS
Alternatively, maybe you intended to index the list with item and not items? In which case you should do
PositionOfItems[item]=HERO_INVENTORY_POS
Depending in how you defined PositionOfItems
In your line of code
PositionOfItems[items]=HERO_INVENTORY_POS
You are treating it as a dictionary instead of a list, where items is the key and HERO_INVENTORY_POS is the value. When I tried reproducing your code snippet(below), my error was that the dictionary was not defined as empty before its use, and if defined as a list I received the TypeError: list indices must be integers, not str.
with open("test.txt", 'r') as f:
dict = {} #This line
for item in f:
dict[item] = 999
print item,
If you have assigned PositionOfItems as a list, then the issue is that you would be referring to indexes that have not been defined (or at least not show in your code here) and are attempting to reference them with a string (items) instead of an integer. (Giving you the TypeError)

Python3: Calling functions saved as values (strings) in a dictionary

Background:
I am reading a python file (.py) that has a number of functions defined and using a regex to get the names of all the functions and store them in a list.
d_fncs = {}
list_fncs = []
with open('/home/path/somefile.py', 'r') as f:
for row in f:
search = re.search(r'def (.*)\(', row)
if search:
list_fncs.append(search.group(1))
The above works fine and as expected returns a list of of the function names as strings. I have another list which I plan to use as a counter.
counter = [str(i) for i in range(1,len(list_fncs)+1)]
Finally, I zip the two lists to get a dictionary where the 'keys' are numbers and the associated 'values' are function names
d_fncs = dict(zip(counter,list_fncs))
The problem:
The intent here is to ask user for an input which would be matched with the key of this dictionary (counter). Once the key is matched, the function associated with it is executed. Something like this happens later in the code:
def option_to_run(check, option_enter_by_user):
if check == 'True':
return (connection(d_fncs[option]))
def connection(fnc):
conn_name = Connect(some args..) #class imported
fnc(conn_name)
In this case, as the values from dict are string, I get the following error:
File "/home/path/filename.py", line 114, in connection
fnc(conn_name)
TypeError: 'str' object is not callable
However, if I manually make a dict and run it then I have no issues and functions work as expected:
d_fncs_expected = {'1': function1, '2': function2, ....}
Right now what I am getting is this:
d_fncs = {'1': 'function1', '2': 'function2', ....}
....what can I do to get the dictionary to work in a way so I can call these functions? I want the values not to be strings but a type:class
Replace
fnc(conn_name)
to
eval(fnc)(conn_name) # or eval(fnc(conn_name))
or
globals()[fnc](conn_name)
For example
def myfn(arg):
print(arg +" is printed")
d = {1: 'myfn'}
fun_name = d[1] # 'myfn'
>>>fun_name("something")
TypeError: 'str' object is not callable
>>>eval(fun_name)("something")
something is printed
>>>globals()[fun_name]("someting")
something is printed

Python 'NoneType' itterable in list operation

I am writing a function to remove duplication in one list. For specific:
input : a list
output: a list without any duplication
this is my code:
def remove_duplicate(s_list):
for member in s_list:
for other in s_list.remove(member):
if other == member:
s_list.remove(other)
return s_list
After that, I try to run remove_duplicate([1,2,3,4]) and the error is
for other in s_list.remove(member):
TypeError: 'NoneType' object is not iterable
I would suggest to work with two lists instead of changing one list in-place, if possible.
If order is not important, you can use a set:
dup_list = [1,1,2,3,2,5,2]
dupfree_list = list(set(dup_list))
Otherwise, if the order of elements is important, you can note which elements you have already seen:
dupfree_list = []
for e in dup_list:
if e not in dupfree_list:
dupfree_list.append(e)
I think the most Pythonic way is to use a set which removes duplicates:
listwithduplicates = [1,2,3,3]
listwithduplicates = set(listwithduplicates)
The result is:
{2,1,3}
Note that sets are not ordered the way lists are.

Categories

Resources