【问题标题】:Iterating over a dictionary and creating an object for each key with its values within the same object遍历字典并为每个键创建一个对象,其值在同一对象中
【发布时间】:2019-12-04 19:47:50
【问题描述】:
import random
import os
import json

class User:
    def _init_(self, username, password, balance):
        self.username = username
        self.password = password
        self.balance = balance



def file_read(source):
    with open (source) as file:
        data = file.read()
        dictionary = json.loads(data)
        return dictionary

然后外部文件就是这个

{"John":["pass123", 2000], "Jenson": ["pass123", 2000]}

我最初的想法是使用 for items in dict 但我不确定如何从最好由用户名命名的对象中创建多个对象 谢谢。

【问题讨论】:

  • 上面显示的当前输入文件需要什么输出?
  • 问题是什么?
  • 当我使用``data = file_read(file directory)```
  • 它将返回存储在外部文件中的字典并将其存储在该变量中
  • 更新:感谢所有帮助的人,现在可以正常使用

标签: python dictionary oop


【解决方案1】:

使用 dict 理解和 var-args 的简单解决方案:

{ k: User(k, *v) for k, v in file_read(filename).items() }

或者你可以通过解构来做到这一点:

{ k: User(k, pw, bal) for k, (pw, bal) in file_read(filename).items() }

【讨论】:

    【解决方案2】:

    可能是您要查找的内容。请记住它是__init__ 而不是_init_

    import json
    
    def file_read(source):
        with open(source) as file:
            data = file.read()
            dictionary = json.loads(data)
            return dictionary
    
    class User:
        def __init__(self, username, password, balance):
            self.username = username
            self.password = password
            self.balance = balance
    
        def __str__(self): # String representation of the object for the output.
            return f"{self.username}@{self.password} with balance of {self.balance}"
    
    dictionary = file_read("file.json")
    
    users = []
    for key, item in dictionary.items():
        user = User(key, item[0], item[1])
        users.append(user)
    
    # Printing results for output sake.
    for user in users:
        print(user)
    

    输出:

    John@pass123 with balance of 2000
    Jenson@pass123 with balance of 2000
    

    file.json 为:

    {"John":["pass123", 2000], "Jenson": ["pass123", 2000]}
    

    【讨论】:

    • 对不起,我刚开始使用 oop,我将查看您发送的代码并尝试实现此谢谢
    • 无需抱歉——我们都是从某个地方开始的。倒数第二个for-loop 是我们通过使用dictionary.items() 迭代字典项目的地方,在user = User(key, item[0], item[1]) 行上我们正在创建我们的用户对象。
    【解决方案3】:

    我认为您要问的是为文件中的每个名称创建对象。

    class User:
        def __init__(self, username, password, balance):
            self.username = username
            self.password = password
            self.balance = balance
    def file_read(source):
        with open (source) as file:
           data = file.read()
           dictionary = json.loads(data)
           return dictionary
    dicValuesRead = file_read(source)
    d = {}
    for k,v in dicValuesRead.items():
        d[k] = User(k, v[0], v[1])
    
    print (d)
    

    【讨论】:

    • file_read 需要在 class User 之外才能被调用。
    • 啊,是的,在这上面编辑代码很难……我会修复它,谢谢
    • 谢谢你,我会看看字典理解
    • 是的,理解是更清晰的解决方案。我喜欢下面的@kaya3 回答。也不是像菲利普提到的那样,你需要在你的代码中使用 init ..跨度>
    【解决方案4】:

    最好用用户名命名

    这是有问题的,对于您问题的这一部分,最常见的解决方案是创建一个包含 {username:object} 对的字典。见How do I create a variable number of variables?

    你的函数返回一个字典。

    • 遍历dictionary items 将产生(name,(password,balance)) 元组
    • 为每个项目提取单独的name,(password,balance)= item
    • 将这些传递给类以创建一个新对象并将其添加到字典中
    • new_dict[name] = object

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2021-06-02
      • 1970-01-01
      • 2013-03-02
      相关资源
      最近更新 更多