W
W
Worgen2018-09-24 03:53:53
Python
Worgen, 2018-09-24 03:53:53

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')

What was originally in newMessage
{'messages': {'count': 1, 'items': [{'peer_id': 111111, 'is_hidden': False, 'from_id': 111111, 'fwd_messages': [], ' out': 0, 'conversation_message_id': 1131, 'random_id': 0, 'date': 1537747480,
'text': '123', 'id': 1111, 'important': False, 'attachments': []} ]}, 'new_pts': 111111, 'conversations': [{'out_read': 6160108, 'last_message_id': 66011108, 'in_read': 0, 'can_write': {'allowed': Tr
ue}, 'peer': {'type': 'user', 'id': 1111, 'local_id': 11111}, 'unread_count': 2}], 'profiles': [{'id': 11111, 'first_name':'Maria', 'last_name': 'Old'}], 'history': }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
AlexandrBirukov, 2018-09-24
@Worgen

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)

and now to extract data from json footcloths, you can do the following:
test = get_value(newMessage, "messages.items.peer_id")

S
smer44, 2018-09-24
@smer44

test= newMessage.get('messages',default).('items')[0].('peer_id')
default = {'items': ['peer_id' : -42] }
or make the data simpler if you can

T
Teslaman, 2018-09-24
@Teslaman

test = newMessage["messages"]["items"][0]["peer_id"]

In fact, this is not the best way to work with VK api. It is much more convenient to take a ready-made library that will take over the job of serializing json into convenient Python objects. You will only need to think about the business logic of the application.

L
lega, 2018-09-24
@lega

try:
  test = newMessage["messages"]["items"][0]["peer_id"]
except KeyError:
  test = None

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question