Solved: how to extract keys from dictreader python

The main problem is that dictreader does not provide a way to extract keys from the dictionary. dictionary

I have a dictionary that I am trying to extract keys from. The dictionary is called "dictreader" and looks like this:
{'id': '1', 'name': 'John', 'age': '20', 'city': 'New York'}

I want to extract the keys from this dictionary so that I can use them in a for loop. This is what I have tried:
for key in dictreader.keys():
print(key)

However, this gives me the following error:

"AttributeError: type object 'dictreader' has no attribute 'keys'"

A:

.keys() is a method of dictionaries, not of objects in general. You are trying to call it on an object of type type, which does not have such a method (hence the error message). To get the keys of your dictionary, you need to call .keys(): for key in dictreader.keys(): ... . If you want to iterate over all attributes of an object, use .__dict__.items(): for attr_name, attr_value in dictreader.__dict__.items(): ... . If you want all attributes except for those starting with two underscores (private variables and methods are considered part of an object's interface by convention only; they are not enforced by Python itself.) use [attr for attr in dir(obj) if not attr[0] == "_"]):

$ python3 -c "class A: pass; print([attr for attr in dir(A()) if not attr[0] == "_""])"" ['<class __main__.'A'>'

Related posts:

Leave a Comment