How to get first value in 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 element in my dicitionary?

I want at the end of the list:

myList = [1609.32,57813.48,991.31]
+4
source share
6 answers

Try as follows:

my_list = [elem[0] for elem in your_dict.values()]

Offtopic: I think you should not use camelcase, this is not a python way.

UPD: inspectorG4dget notes that the result will be different. It is right. You must 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) })
+7
source

one line ...

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

result:

>>> print myList 
[1609.32, 991.31, 57813.48]
0
source
myList = []  
for k,v in myDict.items()  
    myList.append(v[0])
0

, :

from collections import OrderedDict
ordered = OrderedDict(
    ('BigMeadow2_U4', (1609.32, 22076.38, 3.98)),  
    ('MooseRun', (57813.48, 750187.72, 231.25)),  
    ('Hwy14_2', (991.31, 21536.80, 6.47)) 
)
first_values = [v[0] for v in ordered.values()]

, .

0

. , ,

d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2}
print(d)
def getDictKeyandValue(dict,n): 
    c=0
    mylist=[]
    for i,j in d.items():
        c+=1
        if c==n:

            mylist=[i,j]
            break
    return mylist   

print(getDictKeyandValue(d,2))
-1

(getDictKeyandValue (, 1))

-2
source

Source: https://habr.com/ru/post/1528063/


All Articles