如何获取python字典中的第一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21930498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the first value in a python dictionary
提问by ustroetz
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]
采纳答案by Andrey Rusanov
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
Offtop:我认为你不应该使用驼峰命名法,这不是 python 方式
UPD: inspectorG4dget notes, that result won't be same. It's right. You should use collections.OrderedDict to implement this correctly.
UPD:inspectorG4dget 指出,结果不会相同。这是正确的。您应该使用 collections.OrderedDict 来正确实现这一点。
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) })
回答by Houcheng
one lines...
一行...
myList = [myDict [i][0] for i in sorted(myDict.keys()) ]
the result:
结果:
>>> print myList
[1609.32, 991.31, 57813.48]
回答by linpingta
myList = []
for k,v in myDict.items()
myList.append(v[0])
回答by DominiCane
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.
输出顺序将与您的输入顺序完全相同。
回答by kamran shaik
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))
回答by kamran shaik
for getting first value
获得第一个价值
print(getDictKeyandValue(d,1))
打印(getDictKeyandValue(d,1))

