Python dict object has no attribute remove

How can I correct the error ‘ AttributeError: ‘dict_keys’ object has no attribute ‘remove’ ‘?

The formatting syntax makes it clear that you can only access attributes (a la ) or index (a la ) the placeholders (taken from «Format String Syntax»): With Python 3.6 you can easily do this with f-strings, you don’t even have to pass in : Solution 2: Solution 3: https://www.youtube.com/watch?v=LHCVNtxb4ss) AttributeError: ‘dict_keys’ object has no attribute ‘remove’ Solution: In Python 3, returns a dict_keys object (a view of the dictionary) which does not have method; unlike Python 2, where returns a list object.

How can I correct the error ‘ AttributeError: ‘dict_keys’ object has no attribute ‘remove’ ‘?

I was trying shortest path finder using dijkstra algorithm but It seems not working. Can’t figure out what the problem is. Here are the code and the error message. (I’m working on Python 3.5. https://www.youtube.com/watch?v=LHCVNtxb4ss)

graph = < 'A': , 'B': , 'C': , 'D': , 'E': , 'F': , 'G': , 'H': , 'I': <>, 'J': , > def dijkstra(graph, start, end): D = <> P = <> for node in graph.keys(): D[node]= -1 P[node]="" D[start]=0 unseen_nodes=graph.keys() while len(unseen_nodes) > 0: shortest=None node=' ' for temp_node in unseen_nodes: if shortest==None: shortest = D[temp_node] node = temp_node elif D[temp_node] 

AttributeError: 'dict_keys' object has no attribute 'remove'

In Python 3, dict.keys() returns a dict_keys object (a view of the dictionary) which does not have remove method; unlike Python 2, where dict.keys() returns a list object.

>>> graph = >>> keys = graph.keys() >>> keys dict_keys(['a']) >>> keys.remove('a') Traceback (most recent call last): File "", line 1, in AttributeError: 'dict_keys' object has no attribute 'remove' 

You can use list(..) to get a keys list:

>>> keys = list(graph) >>> keys ['a'] >>> keys.remove('a') >>> keys [] 

How can i fix AttributeError: 'dict_values' object has no, len(mydict) is sufficient, since in this context the len of a dict is the number of keys. No need to produce a list of the values or keys. And making a …

Formatting dict keys: AttributeError: 'dict' object has no attribute 'keys()'

What is the proper way to format dict keys in string?

>>> foo = >>> "In the middle of a string: ".format(**locals()) 
"In the middle of a string: ['one key', 'second key']" 
Traceback (most recent call last): File "", line 1, in "In the middle of a string: ".format(**locals()) AttributeError: 'dict' object has no attribute 'keys()' 

But as you can see, my dict has keys:

>>> foo.keys() ['second key', 'one key'] 

You can't call methods in the placeholders. You can access properties and attributes and even index the value - but you can't call methods:

class Fun(object): def __init__(self, vals): self.vals = vals @property def keys_prop(self): return list(self.vals.keys()) def keys_meth(self): return list(self.vals.keys()) 

Example with method (failing):

>>> foo = Fun() >>> "In the middle of a string: ".format(foo=foo) AttributeError: 'Fun' object has no attribute 'keys_meth()' 

Example with property (working):

>>> foo = Fun() >>> "In the middle of a string: ".format(foo=foo) "In the middle of a string: ['one key', 'second key']" 

The formatting syntax makes it clear that you can only access attributes (a la getattr ) or index (a la __getitem__ ) the placeholders (taken from "Format String Syntax"):

The arg_name can be followed by any number of index or attribute expressions. An expression of the form '.name' selects the named attribute using getattr() , while an expression of the form '[index]' does an index lookup using __getitem__() .

With Python 3.6 you can easily do this with f-strings, you don't even have to pass in locals :

>>> foo = >>> f"In the middle of a string: " "In the middle of a string: dict_keys(['one key', 'second key'])" >>> foo = >>> f"In the middle of a string: " "In the middle of a string: ['one key', 'second key']" 
"In the middle of a string: <>".format(list(foo.keys())) 
"In the middle of a string: <>".format([k for k in foo]) 

As it was said by others above you cannot do it in the way you would prefer, here are additional information to follow python string format calling a function

Python - 'dict' object has no attribute 'value' but I see it, This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was …

Strange error message: 'dict_keys' object has no attribute 'pop'

I have a strange problem with a code I'm trying to run on jupyter notebook(python version - 3.7.6)

the code in this link (https://towardsdatascience.com/to-all-data-scientists-the-one-graph-algorithm-you-need-to-know-59178dbb1ec2) was kind of out of date because of the python version it was written on. I changed the ".iteritems" to ".items" and it worked well up to this part:

graph = Graph(g) graph.add_edge(("Mumbai", "Delhi"),400) graph.add_edge(("Delhi", "Kolkata"),500) graph.add_edge(("Kolkata", "Bangalore"),600) graph.add_edge(("TX", "NY"),1200) graph.add_edge(("ALB", "NY"),800) g = graph.adj_mat() def bfs_connected_components(graph): connected_components = [] nodes = graph.keys() while len(nodes)!=0: start_node = nodes.pop() queue = [start_node] #FIFO visited = [start_node] while len(queue)!=0: start = queue[0] queue.remove(start) neighbours = graph[start] for neighbour,_ in neighbours.items(): if neighbour not in visited: queue.append(neighbour) visited.append(neighbour) nodes.remove(neighbour) connected_components.append(visited) return connected_components print bfs_connected_components(g) 

It gives me this error File "", line 32 print bfs_connected_components(g) ^ SyntaxError: invalid syntax

So i tried to take off print and let just bfs_connected_components(g) to find what the debugger would return me.

When I run the code without the print command it returns me the following error:

AttributeError Traceback (most recent call last) in 30 return connected_components 31 ---> 32 bfs_connected_components(g) in bfs_connected_components(graph) 14 15 while len(nodes)!=0: ---> 16 start_node = nodes.pop() 17 queue = [start_node] #FIFO 18 visited = [start_node] AttributeError: 'dict_keys' object has no attribute 'pop' 

which is weird, because there is .pop commands in the previous codes in this link and it worked well without any errors, except for the .iteritems expressions.

Like the other issues you mentioned (such as the missing parentheses in print , and the items to iteritems change), this is a Python version issue. In Python 3, pop doesn't work on dict_keys.

To work around this, you can make it a list. In your code, do nodes = list(graph.keys()) .

Python - 'dict' object has no attribute 'has_key', 185. While traversing a graph in Python, a I'm receiving this error: 'dict' object has no attribute 'has_key'. Here is my code: def find_path (graph, …

When I tried to sort a list, I got an error 'dict' object has no attribute

My code which created the list is:

choices = [] for bet in Bet.objects.all(): #. #Here is code that skip loop if bet.choice exist in choices[] #. temp = < 'choice':bet.choice, 'amount':bet.sum, 'count':bets.filter(choice=bet.choice).count()>choices.append(temp) choices.sort(key=attrgetter('choice'), reverse=True) choices.sort(key=attrgetter('amount'), reverse=True) choices.sort(key=attrgetter('count'), reverse=True) 

I have to sort by list because model orderby() cant sort by count(),can it?

Your dictionaries have no choice , amount or count attributes. Those are keys , so you need to use an itemgetter() object instead.

from operator import itemgetter choices.sort(key=itemgetter('choice'), reverse=True) choices.sort(key=itemgetter('amount'), reverse=True) choices.sort(key=itemhetter('count'), reverse=True) 

If you want to sort by multiple criteria, just sort once, with the criteria named in order:

choices.sort(key=itemgetter('count', 'amount', 'choice'), reverse=True) 

You probably want to have the database do the sorting, however.

Python - 'dict' object has no attribute 'id', Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Источник

How can I correct the error ' AttributeError: 'dict_keys' object has no attribute 'remove' '?

In Python 3, dict.keys() returns a dict_keys object (a view of the dictionary) which does not have remove method; unlike Python 2, where dict.keys() returns a list object.

>>> graph = >>> keys = graph.keys() >>> keys dict_keys(['a']) >>> keys.remove('a') Traceback (most recent call last): File "", line 1, in AttributeError: 'dict_keys' object has no attribute 'remove' 

You can use list(..) to get a keys list:

>>> keys = list(graph) >>> keys ['a'] >>> keys.remove('a') >>> keys [] 

Answer by Foster Garcia

How can I correct the follow error ' AttributeError: 'dict_keys' object has no attribute 'remove' '? ,' AttributeError: 'dict_keys' object has no attribute 'remove' ',The specific error is 'dict_keys' object has no attribute 'remove'. That's how I know that python isn't finding a dict.,You are getting this problem when you load the matlab file and the code expecting a dict where it doesn't find a dict.

I was trying to follow the example of "https://github.com/EBjerrum/Deep-Chemometrics/blob/master/Deep_Chemometrics_with_data_augmentation.py.ipynb", but when executing the first part of the code I immediately get the error.

#code import scipy.io as sio import numpy as np def get_xY(filename, maxx=600): #sio.whosmat(filename) matcontents = sio.loadmat(filename) keys = matcontents.keys() for key in list(keys): if key[0] == '_': keys.remove(key) keys.sort() d = <> for key in keys: data = matcontentsPython dict object has no attribute remove[0][0] if key[-1] == "Y": Ydata = data[5] dPython dict object has no attribute remove = Ydata else: xdata = data[5][. maxx] dPython dict object has no attribute remove = xdata d["axisscale"]= data[7][1][0][0][:maxx].astype(np.float) return d filename = 'Dataset/nir_shootout_2002.mat' dataset = get_xY(filename) 

Answer by Kailey Gilmore

In Python 3, dict.keys() returns a dict_keys object (a view of the dictionary) which does not have remove method; unlike Python 2, where dict.keys() returns a list object.,If you really must have mutual imports in Python, the way to do it is to import them within a function:,AttributeError: 'dict_keys' object has no attribute 'remove',I was trying shortest path finder using dijkstra algorithm but It seems not working. Can't figure out what the problem is. Here are the code and the error message. (I'm working on Python 3.5. https://www.youtube.com/watch?v=LHCVNtxb4ss)

I was trying shortest path finder using dijkstra algorithm but It seems not working. Can't figure out what the problem is. Here are the code and the error message. (I'm working on Python 3.5. https://www.youtube.com/watch?v=LHCVNtxb4ss)

graph = < 'A': , 'B': , 'C': , 'D': , 'E': , 'F': , 'G': , 'H': , 'I': <>, 'J': , > def dijkstra(graph, start, end): D = <> P = <> for node in graph.keys(): D[node]= -1 P[node]="" D[start]=0 unseen_nodes=graph.keys() while len(unseen_nodes) > 0: shortest=None node=' ' for temp_node in unseen_nodes: if shortest==None: shortest = D[temp_node] node = temp_node elif D[temp_node] 

Answer by Whitley Davidson

As you are in python3 , use dict.items() instead of dict.iteritems() iteritems() was removed in python3, so you can't use this method anymore. Take a look at Python 3.0 Wiki Built-in Changes section, where it is stated: Removed dict.iteritems(), dict.iterkeys(), and dict.itervalues(). Instead: use dict.items(), dict.keys(), dict.values() respectively. 

Источник

Читайте также:  Java to excel code
Оцените статью