遍历字典并为每个键创建一个对象,其键值在同一对象内

时间:2019-12-04 19:47:50

标签: python dictionary oop

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 但是我不确定如何从最好由用户名命名的对象中创建多个对象 谢谢。

4 个答案:

答案 0 :(得分:1)

可能是您要找的东西。请记住,它是__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]}

答案 1 :(得分: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 :(得分:0)

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

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)

答案 3 :(得分:0)

  

最好以用户名命名

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

您的函数返回一个字典。

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