I have a dictionary like this:
myDict = {
'BigMeadow2_U4': (1609.32, 22076.38, 3.98),
'MooseRun': (57813.48, 750187.72, 231.25),
'Hwy14_2': (991.31, 21536.80, 6.47)
}
How can I get the first value of each item in my dicitionary?
I want in the end a list:
myList = [1609.32,57813.48,991.31]
Get first value in a dictionary using item() item() function of dictionary returns a view of all dictionary in form a sequence of all key-value pairs. From this sequence select the first key-value pair and from that select first value.
Method #2 : Using next() + iter() This task can also be performed using these functions. In this, we just take the first next key using next() and iter function is used to get the iterable conversion of dictionary items. So if you want only the first key then this method is more efficient. Its complexity would be O(1).
The easiest way to get the first item from a dictionary is with the items() function. The items() function returns a dict_items object, but we can convert it to a list to easily and then access the first element like we would get the first item in a list.
Try this way:
my_list = [elem[0] for elem in your_dict.values()]
Offtop: I think you shouldn't use camelcase, it isn't python way
UPD: inspectorG4dget notes, that result won't be same. It's right. You should use collections.OrderedDict to implement this correctly.
from collections import OrderedDict
my_dict = OrderedDict({'BigMeadow2_U4': (1609.32, 22076.38, 3.98), 'MooseRun': (57813.48, 750187.72, 231.25), 'Hwy14_2': (991.31, 21536.80, 6.47) })
one lines...
myList = [myDict [i][0] for i in sorted(myDict.keys()) ]
the result:
>>> print myList
[1609.32, 991.31, 57813.48]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With