How to get the first value in a python dictionary

前端 未结 6 867
遇见更好的自我
遇见更好的自我 2020-12-11 01:02

I have a dictionary like this:

myDict = {  
    \'BigMeadow2_U4\': (1609.32, 22076.38, 3.98),  
    \'MooseRun\': (57813.48, 750187.72, 231.25),  
    \'Hw         


        
相关标签:
6条回答
  • 2020-12-11 01:29
    myList = []  
    for k,v in myDict.items()  
        myList.append(v[0])
    
    0 讨论(0)
  • 2020-12-11 01:33

    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) })
    
    0 讨论(0)
  • 2020-12-11 01:36

    one lines...

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

    the result:

    >>> print myList 
    [1609.32, 991.31, 57813.48]
    
    0 讨论(0)
  • 2020-12-11 01:40

    If you want ordered dictionary, use:

    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()]
    

    The output order will be exactly as your input order.

    0 讨论(0)
  • for getting first value

    print(getDictKeyandValue(d,1))

    0 讨论(0)
  • 2020-12-11 01:51

    Try this.Type the dictionary and the position you want to print in the function

    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))
    
    0 讨论(0)
提交回复
热议问题