pythonordereddict

How to extract second values elements only in every keys in an OrderedDict?


SO, i have this code, i want to extract the second values elements only in every keys in an OrderedDict, i dont want to use for loop,any idea on this ?

from collections import OrderedDict

regDict= OrderedDict()
regDict["glenn"] = (100,200)
regDict["elena"] = (10,20)
print("values",list(regDict.values())[0][1])
print("values",list(regDict.values())[1][1])

prints:

values 200
values 20

target output:

values 200,20    # or values ( 200,20 )

Solution

  • To do it without using explicit loops (I'd say that just putting for inside a list comprehension syntax still makes use of a for loop), you can use map to only get the second value back as a list, then join those values together with ','.join() for printing out:

    >>> ','.join(map(lambda x: str(x[1]), regDict.values()))
    '200,20'
    

    The map call uses the lambda function to return the second value ([1]) for each original value:

    >>> list(map(lambda x: str(x[1]), regDict.values()))
    ['200', '20']
    

    Calling ','.join() with this list as an argument gives you a concatenated string back with each value separated by ,.