简体   繁体   English

如何用字典中的可选元素列表创建对象?

[英]How to create objects with a list of optional elements from a dictionary?

I've been learning how to program and this is problem I'm having trouble solving: 我一直在学习如何编程,这是我无法解决的问题:

I have a class User that takes 4 parameters, 2 required and 2 optional: 我有一个类User,它带有4个参数,2个必需参数和2个可选参数:

class User:
    def __init__(self, user_id, first_name, last_name='', username=''):
        self.user_id = user_id
        self.first_name = first_name
        self.last_name = last_name
        self.username = username

then I make a function to create those objects, they take a dictionary and use looks in the keys to create the objects 然后我创建一个函数来创建这些对象,它们使用字典并使用键中的外观创建对象

users={}


def user_register(user_info):
if user_info['id'] in users:
    pass
else:
    print('cadastrando...')
    users[user_info['id']] = User(user_info['id'], user_info['first_name'],
                                  user_info['last_name'], user_info['username'])

example_userinfo1 = {'id':111, 'first_name':'john', 'last_name':'smith', 'username':'@johnsmith'}

example_userinfo2 = {'id':222, 'first_name':'bob'}

so like this it only works if the dictionary given has all the four keys,which is the case of example_userinfo1, but not the case for example_userinfo2 (only ID and first_name are mandatory). 因此,仅当给定的字典具有所有四个键时才起作用,例如example_userinfo1,而example_userinfo2则不是(仅ID和first_name是必需的)。 I would like to know what is the way of checking if the key exists before passing it as an argument, I tried something like this with no success: 我想知道在将密钥作为参数传递之前检查密钥是否存在的方法,我尝试了类似的尝试,但没有成功:

User(user_info['id'], user_info['first_name'],
        if 'last_name' in user_info: last_name=user_info['last_name'],
        if 'username' in user_info: username=user_info['username'])

so what is a good way to overcome this problem? 那么解决这个问题的好方法是什么呢? also I would like to know if there are many signs of bad practices on my code (as I am trying to start paying attention to those things) 我也想知道我的代码中是否有许多不良做法的迹象(因为我试图开始注意那些事情)

Make your dictionary keys correspond dir to the argument names, just apply the whole dictionary as keyword arguments: 使您的字典键与dir对应于参数名称,只需将整个字典用作关键字参数即可:

user_id = user_info.pop('id')
users[user_id]  = User(user_id, **user_info)

I used dict.pop() to remove the 'id' key as your class expects user_id instead. 我用dict.pop()删除了'id'键,因为您的班级希望使用user_id You already supplied default values for any missing keys. 您已经为所有缺少的键提供了默认值。

Otherwise, you could have used dict.get() to return an empty string if a key is missing: 否则,如果缺少键,则可以使用dict.get()返回空字符串:

User(user_info['id'], user_info['first_name'],
    last_name=user_info.get('last_name', ''),
    username=user_info.get('username', ''))

Better way to do this is to unpack the dict using ** . 更好的方法是使用**解开dict For example: 例如:

>>> userinfo = {'user_id':222, 'first_name':'bob'}
#                  ^  I am using `user_id` instead of `id`. 
#                     Continue reading for explanation
>>> User(**userinfo)
<__main__.User instance at 0x7f1f4c70cf80>

When you unpack the dict within the function call, it maps the dict key with the function parameters and the dict value as the value of parameter. 当您在函数调用中解开dict时,它会将dict键与函数参数映射,并将dict值映射为parameter的值。 So in this case, your function call was like: 因此,在这种情况下,您的函数调用就像:

User(user_id=222, first_name='bob')

Edit: Based on additional information from user as id is returned from API. 编辑:基于用户的其他信息,因为从API返回id And it is not good to use id as variable since id() is built-in function in python. 由于id()是python中的内置函数,因此将id用作变量不是很好。 In this case, you can modify dict explicitly as: 在这种情况下,您可以将dict明确修改为:

>>> userinfo = {'id':222, 'first_name':'bob'}
>>> userinfo['user_id'] = userinfo['id']
>>> del userinfo['id']
>>> userinfo
{'first_name': 'bob', 'user_id': 222}   # Final value hold by dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM