将字典的第一项存储在变量中

时间:2017-09-28 10:27:19

标签: python python-3.x dictionary methods

我想编写一个接受字典作为参数的函数,并将函数存储在函数中的第一项或字典中的第一个值中。我如何在Python 3中执行此操作?

例如:

random_function({'a':1, 'b':2, 'c':3})
> first_item = 'a'
> first_value = 1

3 个答案:

答案 0 :(得分:3)

默认情况下,字典不是有序的,因此您无法引用“第一个”字典项,因为这将始终更改。如果要引用字典的“第一个”键/值,则需要使用OrderedDict数据结构。这将存储输入字典值的顺序

import csv
from collections import OrderedDict  
# you can use a normal dict if the order of the rows does not matter

with open('file.csv') as f:
  r = csv.reader(f)
  d = OrderedDict()
  for row in r:
    if row[0] not in d or d[row[0]][2] < row[2]:
      d[row[0]] = row
d.values()
# [['cdfg', '324', '2017-09-27 18:38:38'], ['abcd', '123', '2017-09-27 19:38:38']]

with open('file_out.csv', 'w') as f:
  w = csv.writer(f)
  w.writerows(d.values())

答案 1 :(得分: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)

答案 2 :(得分:-1)

使用下一步,您可以手动使用迭代器:

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.