[英]How to set a var if it exists in a dict?
I'm querying an API endpoint which brings information about events. 我正在查询带事件信息的API端点。 The number of attributes about each event can vary though.
但是,有关每个事件的属性数量可以有所不同。 I now try to do the following:
我现在尝试执行以下操作:
for e in apiResult:
event = Event()
event.street = e['f_street']
event.price = e['f_price']
event.venue_name = e['f_venue_name']
event.start = e['f_start']
# and about 40 more..
event.save()
But I occasionally get key errors. 但是我偶尔会遇到关键错误。 So for each attribute I need to check whether it exists.
因此,对于每个属性,我需要检查它是否存在。 I could of course do this as follows:
我当然可以这样做,如下所示:
if 'f_street' in e:
event.street = e['f_street']
if 'f_price' in e:
event.price = e['f_price']
# etc. etc.
but this doesn't seem very Pythonic. 但这似乎不是Python风格的。 Does anybody know how I can (Pythonically) set an attribute to
event
, only if it exists in the e
dictionary? 有人知道我如何才能(Python)将属性设置为
event
,只要它存在于e
词典中? All tips are welcome! 欢迎所有提示!
I'd recommend to use list of attributes and for loop with if. 我建议使用属性列表,并使用if进行循环。 Something like this:
像这样:
attrs = ['f_street', 'f_price', 'etc']
...
for e in apiResult:
event = Event()
for attr in attrs:
if attr in e:
setattr(event, attr, e[attr])
event.save()
This will also eliminate that 40 lines of attribute settings. 这还将消除40行属性设置。
Btw, docs on python builtin setattr
https://docs.python.org/2/library/functions.html#setattr 顺便说一句,关于Python内置
setattr
文档https://docs.python.org/2/library/functions.html#setattr
dict.get
would help: dict.get
将帮助:
Help on built-in function get:
get(...) method of builtins.dict instance
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
So you could write like this: 所以你可以这样写:
# instead of this:
# event.start = e['f_start']
event.start = e.get('f_start') # And it would be None if key not exists
You can write a function for it: 您可以为其编写一个函数:
def set_if_present(obj, attr_name, dictionary, key):
if key in dictionary:
setattr(obj, attr_name, dictionary[key])
Than you can use it like this: 比您可以像这样使用它:
>>> class O(object):
... pass
...
>>> d = {"a": 0, "b": 1}
>>> o = O()
>>> set_if_present(o, "a", d, "a")
>>> set_if_present(o, "b", d, "b")
>>> set_if_present(o, "c", d, "c")
>>> o.a
0
>>> o.b
1
>>> o.c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'O' object has no attribute 'c'
>>>
or in your case 还是你的情况
for e in apiResult:
event = Event()
set_if_present(event, 'street', e, 'f_street')
set_if_present(event, 'price', e, 'f_price')
set_if_present(event, 'venue_name', e, 'f_venue_name')
set_if_present(event, 'start', e, 'f_start')
# and about 40 more..
event.save()
To be even more pythonic, you can create a list of pairs like [('street', 'f_street'), ('price', 'f_price')...]
and go through this one using the pairs to get and set your values. 要变得更加蟒蛇,您可以创建一个成对的列表,例如
[('street', 'f_street'), ('price', 'f_price')...]
,然后使用这些对进行获取和设置您的价值观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.