Python 将字典的第一项存储在变量中
我想编写一个函数,它接受字典作为参数,并将字典中的第一项或第一个值存储在函数中的变量中。在Python3中如何实现这一点 例如:Python 将字典的第一项存储在变量中,python,python-3.x,dictionary,methods,Python,Python 3.x,Dictionary,Methods,我想编写一个函数,它接受字典作为参数,并将字典中的第一项或第一个值存储在函数中的变量中。在Python3中如何实现这一点 例如: random_function({'a':1, 'b':2, 'c':3}) > first_item = 'a' > first_value = 1 默认情况下,字典不按顺序排列,因此您无法引用“第一个”字典项,因为这将始终更改。如果要引用字典的“第一个”键/值,则需要使用OrderedDict数据结构。这将存储输入字典值的顺序 from collec
random_function({'a':1, 'b':2, 'c':3})
> first_item = 'a'
> first_value = 1
默认情况下,字典不按顺序排列,因此您无法引用“第一个”字典项,因为这将始终更改。如果要引用字典的“第一个”键/值,则需要使用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
使用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.
我希望我已经正确理解了你的问题:
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)
太好了,谢谢。你能解释一下它是如何工作的,比如如果我想存储第二个值,那么我会写什么?