There is a list in it a dictionary. How to cycle correctly in order to get only values (animal, "2337 24", Берта) when outputting?

  my_list = [ {"type": "animals", "number": "2337 24", "name": "Берта"}, {"type": "people", "number": "921-241", "name": "Ваня Пупкин"}, {"type": "people", "number": "103126", "name": "Петя Пупкин"} ] 
  • one
    If you can search by number - [tuple(x.values()) for x in my_list if x['number'] == '2337 24'] - MaxU

3 answers 3

 my_list = [ {"type": "animals", "number": "2337 24", "name": "Берта"}, {"type": "people", "number": "921-241", "name": "Ваня Пупкин"}, {"type": "people", "number": "103126", "name": "Петя Пупкин"} ] for element in my_list: for key in element.keys(): print(element[key]) 
  • one
    In Python, it is not guaranteed that during the iteration the keys will be exactly in the order in which they were specified during dictionary initialization. Therefore, the values ​​are most likely to be displayed not in the same order as in the question, but in some other. When testing this answer, I got the name-number-type in order. - insolor
  • if you are not interested in the order of the keys, then to output the values ​​in an arbitrary order: for d in my_list: print(*d.values()) - jfs

To display values ​​from dictionaries in the selected key order, you can use operator.itemgetter :

 #!/usr/bin/env python from operator import itemgetter getvalues = itemgetter('type', 'number', 'name') for d in my_list: print(*getvalues(d)) 

Result:

 animals 2337 24 Берта people 921-241 Ваня Пупкин people 103126 Петя Пупкин 
     my_list = [ {"type": "animals", "number": "2337 24", "name": "Берта"}, {"type": "people", "number": "921-241", "name": "Ваня Пупкин"}, {"type": "people", "number": "103126", "name": "Петя Пупкин"} ] # Т.к. у словарей в Python нет определенного порядка ключей, то нужно явно задать в каком порядке получать значения: keys = ('type', 'number', 'name') # Выводим тройки значений for item in my_list: print(tuple(item[key] for key in keys)) # ('animals', '2337 24', 'Берта') # ('people', '921-241', 'Ваня Пупкин') # ('people', '103126', 'Петя Пупкин') # Если не нужно выводить, а нужно сформировать список: s = [tuple(item[key] for key in keys) for item in my_list] # Просто вывести значения из словарей в "произвольном" порядке # в моем случае выводит в порядке number - name - type, но на данный порядок полагаться нельзя for item in my_list: print(tuple(item.values())) # ('2337 24', 'Берта', 'animals') # ('921-241', 'Ваня Пупкин', 'people') # ('103126', 'Петя Пупкин', 'people')