亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 Python 字典鍵分配給相應的 Python 對象屬性

如何將 Python 字典鍵分配給相應的 Python 對象屬性

守著星空守著你 2023-07-11 13:51:58
假設我有一個 python 類,例如:class User:    name = None    id = None    dob = None        def __init__(self, id):        self.id = id現在我正在做這樣的事情:userObj = User(id=12) # suppose I don't have values for name and dob yet## some code here and this code gives me name and dob data in dictionary, suppose a function calluser = get_user_data() # this returns the dictionary like {'name': 'John', 'dob': '1992-07-12'}現在,將數據分配給用戶對象的方法是userObj.name = user['name']和userObj.dob = user['dob']。假設,用戶有 100 個屬性。我必須明確分配這些屬性。Python 中有沒有一種有效的方法可以用來將字典中的值分配給對象中的相應屬性?就像,name字典中的鍵被分配給name對象中的屬性。
查看完整描述

5 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

而不是將字典映射到變量鍵。您可以使用它setattr來設置對象中的變量。


class User:

    name = None

    id = None

    dob = None


    def __init__(self, id):

        self.id = id


    def map_dict(self, user_info):

        for k, v in user_info.items():

            setattr(self, k, v)


然后讓鍋爐代碼使用它。



userObj = User(id=12)

user_dict = {

    'name': 'Bob',

    'dob': '11-20-1993',

    'something': 'blah'

}


userObj.map_dict(user_dict)


查看完整回答
反對 回復 2023-07-11
?
LEATH

TA貢獻1936條經驗 獲得超7個贊

首先,Python 中不需要預先聲明屬性。


class Foo:

   bar: int # This actually creates a class member, not an instance member

   ...

如果您想向類實例添加值,只需使用setattr()


d = {

  'prop1': 'value1',

  'prop2': 'value2',

  'prop2': 'value2'

}


x = Foo()


for prop in d.keys():

  setattr(x, prop, d[prop])


查看完整回答
反對 回復 2023-07-11
?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

1.修改類定義

class User():
    def __init__(self, id):
        self.data = {"id":id}
userObj = User(id=12)

2.更新dict()

user = {"name":"Frank", "dob":"Whatever"} # Get the remaining data from elsewhere
userObj.data.update(user) # Update the dict in your userObj
print(userObj.data)

干得好 !


查看完整回答
反對 回復 2023-07-11
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

class User(dict):

    def __init__(self, *args, **kwargs):

        super(User, self).__init__(*args, **kwargs)

        self.__dict__ = self

然后拿起你的字典并執行以下操作:


userObj  = User(dictionary)

setattr()編輯:然后使用該功能


[setattr(userObj, key, item) for key,item in dict.items()]


查看完整回答
反對 回復 2023-07-11
?
莫回無

TA貢獻1865條經驗 獲得超7個贊

如果您確實需要

該解決方案適用于這種情況,其他解決方案不適合您,并且您無法更改您的班級。

問題

如果您無法以任何方式修改您的類,并且您有一個字典,其中包含您想要放入對象中的信息,您可以首先使用檢查模塊獲取類的自定義成員

import inspect
import numpy as np
members = inspect.getmembers(User)

通過以下方式從所有成員中提取自定義屬性:

allowed = ["__" not in a[0] for a in members]

并使用 numpy 列表理解來進行提取本身:

members = np.array(members)["__" not in a[0] for a in members]

修改用戶

假設您有以下用戶和字典,并且您想要將用戶屬性更改為字典中的值(創建新用戶的行為是相同的)

user = User(1)
dic = {"name":"test", "id": 2, "dob" : "any"}

那么你只需使用setattr()

for m in members:
setattr(user, m[0], dic[m[0]])

當然有更好的解決方案,但是如果其他方法不適合您,這可能會派上用場

更新

此解決方案使用基于您使用的類的屬性定義。因此,如果字典有缺失值,這個解決方案可能會有所幫助。否則,拉希德解決方案也適合您


查看完整回答
反對 回復 2023-07-11
  • 5 回答
  • 0 關注
  • 262 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號