Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first value in a python dictionary

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]
like image 657
ustroetz Avatar asked Feb 21 '14 09:02

ustroetz


People also ask

How will you get the first value in a dictionary in Python?

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.

How do you get the first key from a dict in Python?

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).

How do you get the first pair in a dictionary?

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.


2 Answers

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) })
like image 144
Andrey Rusanov Avatar answered Sep 19 '22 14:09

Andrey Rusanov


one lines...

myList = [myDict [i][0] for i in sorted(myDict.keys()) ]

the result:

>>> print myList 
[1609.32, 991.31, 57813.48]
like image 22
Houcheng Avatar answered Sep 21 '22 14:09

Houcheng