简体   繁体   English

如何使用for循环在python中访问字典中的元素?

[英]How to access elements in a dictionary in python with for loop?

I need to extract information from a dictionary, but can't figure how to access data. 我需要从字典中提取信息,但无法确定如何访问数据。

I have: 我有:

from datetime import timedelta, date
from dateutil.relativedelta import relativedelta
import numpy as np

start_date = date(2017,1,1);
final_date = date.today() + relativedelta(months=2);

def datarange(start_date, final_date):
    for n in range((final_date-start_date).days+1):
        yield start_date + timedelta(n)

PayDayTable = {i:np.zeros(5) for i in datarange(start_date, final_date)}

and I can do: 我可以做:

print(PayDayTable)
print(PayDayTable[date.today()])
print(PayDayTable[date.today()][0])
print(PayDayTable[date.today()][1:3])

but when I do: 但是当我这样做时:

for item in PayDayTable:
    print(item)

How can I access the values of the PayDayTable dictionary by iterating over the items with for loop ? 如何通过使用for loop遍历项目来访问PayDayTable dictionary的值?

Edit: 编辑:

I was looking for Python 2 documentation while I was using Python 3.6. 使用Python 3.6时,我一直在寻找Python 2文档。

So instead of doing something like: 因此,与其做类似的事情:

for item in PayDayTable.iteritems():
    pass

I've learned that I should do: 我了解到我应该这样做:

for item in PayDayTable.items():
    print(item[1][0])

type(item) is datetime.date , it is not iterable (you can't do item[0]). type(item)datetime.date ,它是不可迭代的(您不能执行item [0])。 Each element ( item in your code) in your PayDayTable is a date. PayDayTable中的每个元素(代码中的item )都是一个日期。

If you need the dates - just work with elements of PayDayTable . 如果需要日期,请使用PayDayTable元素。 But if you want to get the associated value with the date key by iterating the dictionary using a for loop , then you could do something like: 但是,如果您想通过使用for loop对字典进行迭代来获取带有date键的关联value ,则可以执行以下操作:

for item in PayDayTable:
    print(PayDayTable[item])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM