Home > Software engineering >  How to Display only couple of values in a dictionary
How to Display only couple of values in a dictionary

Time:12-12

I have a dictionary with 2 keys and 1 value. I only want to print the keys and first 3 values in dictionary. Dictionary example:

newdict={('Brain Danielson', 'Canada'): 7887, 
('Kofi Kingston', 'Gana'): 7718, 
('Drew McIntryre', 'England'): 8105,
('John Cena','USA'):9078
}

Output should be:

First: Bryan Danielson, Canada
Second: Kofi Kingston, Gana
Third: Drew McIntryre, England

CodePudding user response:

You can do that in a simple loop with zip() by combining your 3 prompts with the dictionary's keys

for nth,key in zip(('First:','Second:','Third:'),newdict):
    print(nth,*key)

output:

First: Brain Danielson Canada
Second: Kofi Kingston Gana
Third: Drew McIntryre England

zip() will only iterate through the shortest source (in this case your list of prompts) so the 4th and subsequent dictionary keys will not be processed.

If you need the keys assigned to variables, you could use an iterator on the dictionary and get each key using the next() function:

first,second,third = map(next,[iter(newdict)]*3)
print("First:",*first)
print("Second:",*second)
print("Third:",*third) 

There is also a simpler notation (but it is inefficient as it will go through the whole dictionary just to get the first 3 keys):

first,second,third,*_ = newdict

CodePudding user response:

for nth,key in zip(('First:','Second:','Third:'),newdict): print(nth,*key)

  • Related