【发布时间】:2017-09-28 10:27:19
【问题描述】:
我想编写一个函数,它接受字典作为参数,并将字典中的第一项或第一个值存储在函数内的变量中。我如何在 Python 3 中做到这一点?
例如:
random_function({'a':1, 'b':2, 'c':3})
> first_item = 'a'
> first_value = 1
【问题讨论】:
标签: python python-3.x dictionary methods
我想编写一个函数,它接受字典作为参数,并将字典中的第一项或第一个值存储在函数内的变量中。我如何在 Python 3 中做到这一点?
例如:
random_function({'a':1, 'b':2, 'c':3})
> first_item = 'a'
> first_value = 1
【问题讨论】:
标签: python python-3.x dictionary methods
字典默认没有排序,所以你不能引用“第一个”字典项,因为它总是会改变。如果要引用字典的“第一个”键/值,则需要使用 OrderedDict 数据结构。这将存储输入字典值的顺序
from collections import OrderedDict
def random_function(some_dict):
first_key = list(some_dict.items())[0][0]
first_value = list(some_dict.items())[0][1]
print(first_key)
print(first_value)
my_dictionary = OrderedDict({'first': 1, 'second': 2})
random_function(my_dictionary)
> first
> 1
【讨论】:
希望我能正确理解您的问题:
def storeValue(pDict):
if type(pDict) is dict:
if len(pDict) > 0:
storedValue = pDict[pDict.keys()[0]]
#decide what you want to do in the else cases
return storedValue
testDict = {'a': 1,
'b': 2,
'c': 3}
testValue = storeValue(testDict)
【讨论】:
使用 Next,您可以手动使用迭代器:
a = dict(a=1, b=2, c=3, d=4)
b=iter(a.values())
print(next(b)) # print 1
print(next(b)) # print 2
print(next(b)) # print 3
print(next(b)) # print 4
print(next(b)) # Raise 'StopIteration'. You consumed all the values of the iterator.
【讨论】: