Answer the question
In order to leave comments, you need to log in
How to shorten python code?
Good afternoon, do not tell me how can I shorten the code the following code
test=newMessage.get('messages')
test=test.get('items')
test=test[0]
test=test.get('peer_id')
Answer the question
In order to leave comments, you need to log in
you can like this:
def ch_payload(payload):
result = {}
for key, value in payload.items():
if isinstance(value, list):
if value:
value = value[0]
result[key] = value
if isinstance(value, dict):
result[key] = ch_payload(value)
return result
def get_value(payload, item, fallback=None):
"""
Получение вложенных данных
d = {'a': {'b': {'c': 1}}}
get_value(d, 'a.b.c')
"""
serialize_dict = ch_payload(payload)
def getitem(serialize_dict, name):
try:
return serialize_dict[name]
except (KeyError, TypeError):
return fallback
return reduce(getitem, item.split('.'), serialize_dict)
test = get_value(newMessage, "messages.items.peer_id")
test= newMessage.get('messages',default).('items')[0].('peer_id')
default = {'items': ['peer_id' : -42] }
or make the data simpler if you can
test = newMessage["messages"]["items"][0]["peer_id"]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question