Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python version of Object.keys()? [duplicate]

Tags:

python

Suppose I specify a MongoDB cursor with pymongo, which DOES NOT include all fields in the result set like this:

from pymongo import MongoClient
conn = MongoClient('mongodb://localhost:27017')
cur = conn['my_db']['my_collection'].find({},{'_id' : 0, 'my_unwanted_field' : 0})

Is there a function or attribute that will return me the names of the fields present in cur.

Something equivalent on Mongo Shell using findOne would be:

> var cur = findOne({},{'_id' : 0, 'my_unwanted_field' : 0})
> Object.keys(cur)

["field_1", ... , "field_n"]
like image 313
Souradeep Avatar asked Mar 12 '16 04:03

Souradeep


People also ask

Can object have same keys?

Keys in JS objects must be unique.

How do I see properties of an object in Python?

dir() To list all the attributes of an object, use the built-in dir() function. It returns a long list of attribute names, that is, method and variable names of the object. There is a bunch of automatically generated attributes in any Python class.

How do you print object details in python?

To print the attributes of an object we can use “object. __dict__” and it return a dictionary of all names and attributes of object. After writing the above code (python print object attributes), once you will print “x. __dict__” then the output will appear.


1 Answers

Use a loop to iterate the cursor object, then use .keys() to get the keys of any regular python dict, which seems like this:

for item in cur:
    print item.keys()
like image 74
piglei Avatar answered Oct 27 '22 00:10

piglei