I work with Core Telegram API. I get a list of participants in the chat, information on the participant is displayed in this form

{ "_": "pyrogram:ChatMember", "user": { "_": "pyrogram:User", "id": 456488888, "is_self": false, "is_contact": false, "is_mutual_contact": false, "is_deleted": false, "is_bot": false, "first_name": "user" }, "status": "member" } 

or such an example

 { "_": "pyrogram:ChatMember", "user": { "_": "pyrogram:User", "id": 483362460, "is_self": false, "is_contact": false, "is_mutual_contact": false, "is_deleted": false, "is_bot": false, "first_name": "\u0412\u0438\u043a\u0442\u043e\u0440\u0438\u044f", "last_name": "\u041a\u043e\u043c\u0430\u0440\u043e\u0432\u0430", "photo": { "_": "pyrogram:ChatPhoto", "small_file_id": "AQADAgADqacxG6ytzxwACCsSMw4ABDYsn7Nwvs8xgJsAAgI", "big_file_id": "AQADAgADqacxG6ytzxwACCsSMw4ABHg-J0efOQjJgpsAAgI" } }, "status": "member" } 

I want to get the data of a single element, let's say I need all the surnames of users, but this element may not be, how can I skip or replace the missing element, for example with a dash.

I deduce so

data.user.last_name and this last_name may not be there, the script gives an error, what check to make? Maybe I have not quite clearly described my question, not so long ago I began to learn Python.

  • @VasylKolomiets I get the entire list of users, it consists of a set of objects, in the form that I gave in the example, then I pass them through the FOR loop to select elements one by one, and this element is written to the variable data. And I already work with data in the same cycle, then I prescribe the path to the data I need data.user.last_name, but since the surname is not required data for telegrams, the user can not fill this field, and then the element will not have this records, but since I'm trying to call this element on all users, an error occurs. - Denis
  • @VasylKolomiets how to work with PHP in such a way I know, but not in Python. I wanted to get this data simpler, immediately referring to the object element, but this element may not exist at all, I don’t really like it in the data output to telegrams, they could just give out an empty field or False. - Denis
  • one

1 answer 1

An example will help you to understand this:

 d = [ {"a":1, "b":2}, {"a":1, "b":7}, {"a":1}, ] for el in d: print(el.setdefault("b","_")) print(d) 

The output will be:

 2 7 '_' [{'a': 1, 'b': 2}, {'a': 1, 'b': 7}, {'a': 1, 'b': '_'}] 

That is, during the search you need to refer to the dictionary not d['b'] , but d.setdefault("b","_") . But be careful - then the source dictionary changes))

  • one
    Yes, I already figured it out. Thank. - Denis