-6

The problem is that the values ​​are duplicated in the response, how can this be avoided?

users = [{'name': 'Todd', 'phone': '551-1414', 'email': 'todd@gmail.com'},
     {'name': 'Helga', 'phone': '555-1618', 'email': 'helga@mail.net'},
     {'name': 'Olivia', 'phone': '449-3141', 'email': ''},
     {'name': 'LJ', 'phone': '555-2718', 'email': 'lj@gmail.net'},
     {'name': 'Ruslan', 'phone': '422-145-9098', 'email': 'rus-lan.cha@yandex.ru'},
     {'name': 'John', 'phone': '233-421-32', 'email': ''},
     {'name': 'Lara', 'phone': '+7998-676-2532', 'email': 'g.lara89@gmail.com'},
     {'name': 'Alina', 'phone': '+7948-799-2434', 'email': 'ali.ch.b@gmail.com'},
     {'name': 'Robert', 'phone': '420-2011', 'email': ''},
     {'name': 'Riyad', 'phone': '128-8890-128', 'email': 'r.mahrez@mail.net'},
     {'name': 'Khabib', 'phone': '+7995-600-9080', 'email': 'kh.nurmag@gmail.com'},
     {'name': 'Olga', 'phone': '6449-314-1213', 'email': ''},
     {'name': 'Roman', 'phone': '+7459-145-8059', 'email': 'roma988@mail.ru'},
     {'name': 'Maria', 'phone': '12-129-3148', 'email': 'm.sharapova@gmail.com'},
     {'name': 'Fedor', 'phone': '+7445-341-0545', 'email': ''},
     {'name': 'Tim', 'phone': '242-449-3141', 'email': 'timm.ggg@yandex.ru'}]
print(*sorted([lst['name'] for lst in users for k, v in lst.items() if (lst['phone'])[-1].endswith('8')]), end=' ')

printing this:

Helga Helga Helga LJ LJ LJ Maria Maria Maria Riyad Riyad Riyad Ruslan Ruslan Ruslan

gre_gor
  • 6,669
  • 9
  • 47
  • 52
GLITCH
  • 1
  • Is your intention to print just the names where the 'phone' value ends with '8' – DarkKnight Mar 03 '22 at 09:21
  • In this code, `lst` isn't a list but a dictionary, so the name makes no sense; and *there is no reason to iterate over the `.items` anyway*. You get multiple copies in the output because, when the dict matches the criteria, you output the name multiple times - once for each key/value pair, even though there is nothing in the algorithm that cares about those key/value pairs. – Karl Knechtel Mar 03 '22 at 10:10
  • [Chekhov's Gun](https://en.wikipedia.org/wiki/Chekhov%27s_gun) applies to debugging, too: if the code says `for k, v in`, then you should expect it to also use `k` and `v` somewhere. If there is no use for them, then there is no use for the loop, either. – Karl Knechtel Mar 03 '22 at 10:11

1 Answers1

0
print(*sorted([e['name'] for e in users if e['phone'][-1] == '8']))

Output:

Helga LJ Maria Riyad Ruslan
Python learner
  • 1,159
  • 1
  • 8
  • 20
Diego Navarro
  • 9,316
  • 3
  • 26
  • 33