python - 在 Python 中解构字典和对象

标签 python

<分区>

在 Javascript 中,我可以使用 destructuring 从一个 javascript 对象中提取我想要的属性。例如:

currentUser = {
  "id": 24,
  "name": "John Doe",
  "website": "http://mywebsite.com",
  "description": "I am an actor",
  "email": "example@example.com",
  "gender": "M",
  "phone_number": "+12345678",
  "username": "johndoe",
  "birth_date": "1991-02-23",
  "followers": 46263,
  "following": 345,
  "like": 204,
  "comments": 9
}

let { id, username } = this.currentUser;
console.log(id) // 24
console.log(username) //johndoe

对于 Python 字典和 Python 对象,我们在 Python 中有类似的东西吗? Python 对象的 Python 处理方式示例:

class User:
    def __init__(self, id, name, website, description, email, gender, phone_number, username):
        self.id = id
        self.name = name
        self.website = website
        self.description = description
        self.email = email
        self.gender = gender
        self.phone_number = phone_number
        self.username = username
  
current_user = User(24, "Jon Doe", "http://mywebsite.com", "I am an actor", "example@example.com", "M", "+12345678", "johndoe")
    
# This is a pain
id = current_user.id
email = current_user.email
gender = current_user.gender
username = current_user.username
    
print(id, email, gender, username)

编写这 4 行代码(如上面的示例所述)与编写一行代码(如下所述)以从对象中获取我需要的值是一个真正的痛点。

(id, email, gender, username) = current_user

最佳答案

您可以使用标准库中的 operator 模块,如下所示:

from operator import attrgetter
id, email, gender, username = attrgetter('id', 'email', 'gender', 'username')(current_user)
print(id, email, gender, username)

如果你有一个像你的例子中的字典

currentUser = {
  "id": 24,
  "name": "John Doe",
  "website": "http://mywebsite.com",
  "description": "I am an actor",
  "email": "example@example.com",
  "gender": "M",
  "phone_number": "+12345678",
  "username": "johndoe",
  "birth_date": "1991-02-23",
  "followers": 46263,
  "following": 345,
  "like": 204,
  "comments": 9
}

只需使用 itemgetter 而不是 attrgetter:

from operator import itemgetter
id, email, gender, username = itemgetter('id', 'email', 'gender', 'username')(currentUser)
print(id, email, gender, username)

关于python - 在 Python 中解构字典和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54785148/

相关文章:

python - 函数调用开销 - 为什么内置 Python 内置看起来比我的内置更快?

python - 我将如何循环遍历这个文件元组并写入/读取内容?

python - 由于 awsebcli,使用 pip 安装适用于 python 的 MxNet 时出错

python - 使用条件箱范围绘制直方图

python - 禁止 (403) CSRF 验证失败。请求中止。即使使用 {% csrf_token %}

python - python 中用于 multiprocessing.Array 的元组

python - 使用 web2py 修改 SQL 表模式

python - 在 Python 中按索引删除列表中的多个元素

python - 如何使用 Kivy 免费上传 python 文件到 iPhone?

python - 子流程模块工作但不完全工作