Conversion from Python dict to object

Source: Internet
Author: User
The project database is mongoDB and uses pymongo for the find operation. The query result is a string of dict. You need to use xlwt to export the query results as a csv file. For example, there is a piece of data: # dict data row {domain: dmyz.org, page_rank: 2, city: Beijing, country: china} # csv code fields [dom

The project database is mongoDB and uses pymongo for the find operation. The query result is a string of dict. You need to use xlwt to export the query results as a csv file. For example, there is a piece of data: # dict data row = {domain: dmyz.org, page_rank: 2, city: Beijing, country: china} # csv code fields = ['dom

The project database is mongoDB and uses pymongo for the find operation. The query result is a string of dict. You need to use xlwt to export the query result as a csv file. For example, a piece of data is as follows:

# Dict data row = {"domain": "dmyz.org", "page_rank": 2, "city": "Beijing", "country ": "China"} # csv code fields = ['domain ', 'page _ rank', 'country', 'city'] wb = xlwt. workbook () ws = wb. add_sheet ('sheet1') for I in range (len (fields): ws. write (0, I, fields [I])

To obtain the domain value, use row ['domain '], but I want to use the Object Access format, such as row. domain (strictly speaking, the title of this article is ambiguous. My real requirement is to change the dict ACCESS format, and everything in Python is an object and the object is the basis class of dict .)

To meet this requirement, we can use loops to do the following:

def _dict_to_object(d):    class _O: pass    [setattr(_O, _k, d[_k]) for _k in d]    return _Or = _dict_to_object(row)print r.page_rank

The code above defines a class named _ O. Use the setattr function (or the _ setattr _ method) to add dict.

A simpler approach is to use the _ dict _ method of the class:

class Struct:    def __init__(self, **entries):        self.__dict__.update(entries)r = Struct(**row)print row.page_rank

In the above example, there is only one layer of dict. In the actual production environment, this layer of dict is two layers, so the actual code has made some changes:

row = {    "url" : {        "domain" : "dmyz.org"    },    "page_rank" : 2,    "geography" : {        "city" : "Beijing",        "country" : "China"    }}def _dict_to_object(d):    class O: pass    for _k in d:        if type(d[_k]) == dict:            setattr(O, _k, Struct(**d[_k]))        else:            setattr(O, _k, d[_k])    return Or = _dict_to_object(row)print r.url.domain

If there are more layers, change them to iterative writing. I also thought of a simple idea: mongoDB's data is stored in json, so long as dict is replaced when parsing json, that is, object_hook can be added:

from collections import namedtuplerow = '''{    "url" : {        "domain" : "dmyz.org"    },    "page_rank" : 2,    "geography" : {        "city" : "Beijing",        "country" : "China"    }}'''x = json.loads(row, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))print x.url.domain

However, in this way, we need to convert the dict queried by pymongo into str for further processing. It is useless to perform one more step, and we did not expect a good solution for the moment.

Original article address: Convert Python dict to object. Thank you for sharing it with the original author.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.