简体   繁体   English

在python字典中的列表中的字典之间进行迭代-根据条件返回值

[英]Iterate through dictionaries within a list within a dictionary in python - return values based on condition

I want to scrape weather forecast data, more precisely, I want to get data from a dict which has a list with multiple dicts: 我想抓取天气预报数据,更确切地说,我想从具有多个字典列表的字典中获取数据:

  data = {'city': BERLIN,
 'list': [{'date': '2018-10-19 18:00:00',
       'weather': {'temp': 12.86,
                'temp_max': 13.98,
                'temp_min': 12.86},
       'wind': {'deg': 64.5011, 'speed': 1.32}},
      {'date': '2018-10-20 18:00:00',
       'weather': {'temp': 15.86,
                'temp_max': 18.48,
                'temp_min': 12.84},,
       'wind': {'deg': 144.507, 'speed': 1.92}},
    ....

The tricky part is that I want it to return the 'wind' key in the dictionary, where the date is equal to a SATURDAY. 棘手的部分是,我希望它返回字典中的“ wind”键,其中日期等于SATURDAY。

At the end, I'd like to have something like: {Saturday, 'wind': {'deg': 144.507, 'speed': 1.92}} 最后,我想输入以下内容:{星期六,“风”:{“度”:144.507,“速度”:1.92}}

I have looped through 'list', but am lost how to check for Saturday of the date: 我已经遍历了“列表”,但是迷失了如何检查日期的星期六:

    for item in data.get('list'):
print(item.get('date'))
print(item.get('wind'))

returns: 收益:

    2018-10-20 18:00:00
{'speed': 3.92, 'deg': 294.003}
    2018-10-20 21:00:00
{'speed': 3.57, 'deg': 276.001}

To retrieve day and wind keys I tried: 要检索日和风钥匙,我尝试过:

    for item in data.get('list'):
print(item.get(datetime.strptime('date','%Y-%m-%d %H:%M:%S').weekday()))

But get the error that 'time data 'date' does not match format '%Y-%m-%d %H:%M:%S'' 但是会收到错误消息,即'时间数据'日期'与格式'%Y-%m-%d%H:%M:%S'不匹配''

you just have your strptime usage a bit wrong, right now you're telling it to extract date data from the string "date" but what you want is to extract date data from the variable item["date"] : 您的strptime用法有点错误,现在您告诉它从字符串"date"提取日期数据,但您要从变量item["date"]提取日期数据:

for item in data['list']:
    print(datetime.strptime(item["date"],'%Y-%m-%d %H:%M:%S').weekday()))

you also don't need to use the .get() function of dictionaries it's much easier and more acceptable to use the square brackets notation 您也不需要使用字典的.get()函数,使用方括号表示法会更容易并且更容易接受

You should use item['date'] instead of a literal 'date' to reference the item's 'date' value. 您应该使用item['date']而不是文字的'date'来引用该项的'date'值。 The following will return the sub-dict of the wind key of the first Saturday entry: 以下内容将返回第一个星期六条目的wind键的子命令:

next((item['wind'] for item in data['list'] if datetime.strptime(item['date'],'%Y-%m-%d %H:%M:%S').weekday() == 5), {})

You want to do three things. 您想做件事。

  1. Iterate through a list of dictionaries. 遍历字典列表。
  2. Convert date to a week day. date转换为工作日。
  3. Check if week day is Saturday . 检查工作日是否是Saturday

The first step you already got nailed, but you don't need to use get() method to access keys in a dictionary. 第一步已经确定,但是您不需要使用get()方法来访问字典中的键。 Using square brackets works too. 使用方括号也可以。

for item in data['list']: do something


When you are inside the loop you need to grab the value from the date key and then convert it to a datetime object by using the datetime.strptime() function. 在循环中时,您需要从date键中获取值,然后使用datetime.strptime()函数将其转换为datetime object Now you're doing this on a string with the value date . 现在,您将对具有date的字符串执行此操作。

You are doing this: datetime.strptime('date','%Y-%m-%d %H:%M:%S') 您正在执行以下操作: datetime.strptime('date','%Y-%m-%d %H:%M:%S')

It should be this: datetime.strptime(item['date'],'%Y-%m-%d %H:%M:%S') 应该是这样: datetime.strptime(item['date'],'%Y-%m-%d %H:%M:%S')

After you have converted the value from the date key you could store it in a variable and use the strftime() method to convert it to a week day string by calling it with %A . date键转换值之后,可以将其存储在变量中,并使用strftime()方法通过%A调用将其转换为星期几字符串。


The third and last step would be to check if the week day is Saturday . 第三步也是最后一步是检查工作日是否为Saturday You do this with an IF-statement. 您可以使用IF语句执行此操作。

if week_day == 'Saturday': do something


Combining all three steps could result in something looking like this: 将这三个步骤结合在一起可能会导致如下所示:

for item in data['list']:  # step 1

    date = datetime.strptime(item['date'],'%Y-%m-%d %H:%M:%S')  # step 2a
    weekday = date.strftime('%A')  # step 2b

    if weekday == 'Saturday':  # step 3
        print(item)

Thank you antimatter , and especially user347 . 谢谢反物质 ,尤其是user347。 I build upon your suggestions and came up with the following. 我根据您的建议提出以下建议。 Note that I expanded on it since I want to have data for Sat and Sun and for 12 and 15 o'clock. 请注意,由于要获取星期六和星期日以及12点和15点的数据,因此对其进行了扩展。 Is there a good solution for shortening the 4 if-statements? 是否有缩短4个if语句的好方法?

    for item in data['list']:  

date = datetime.strptime(item['date'],'%Y-%m-%d %H:%M:%S')  
weekday = date.strftime('%A') 
time = date.strftime('%H')

if weekday == 'Saturday' and time == '12':
    if item['wind']['speed'] >= 6 and item['wind']['deg'] >= 180:
        print('Perfect conditions on Saturday at 12 -  wind with ' + 
              str(round(item['wind']['speed']* 1.943846, 1)) + 
              ' knots' + ' and direction: '+ str(item['wind']['deg']))

if weekday == 'Saturday' and time == '15':
    if item['wind']['speed'] >= 6 and item['wind']['deg'] >= 180:
        print('Perfect conditions on Saturday at 15  - wind with ' + 
              str(round(item['wind']['speed']* 1.943846, 1)) + 
              ' knots' + ' and direction: '+ str(item['wind']['deg']))

if weekday == 'Sunday' and time == '12':
    if item['wind']['speed'] >= 6 and item['wind']['deg'] >= 180:
        print('Perfect conditions on Sunday at 12 - wind with ' + 
              str(round(item['wind']['speed']* 1.943846, 1)) + 
              ' knots' + ' and direction: '+ str(item['wind']['deg']))

if weekday == 'Sunday' and time == '15':
    if item['wind']['speed'] >= 6 and item['wind']['deg'] >= 180:
        print('Perfect conditions on Sunday at 12 - wind with ' + 
              str(round(item['wind']['speed']* 1.943846, 1)) + 
              ' knots' + ' and direction: '+ str(item['wind']['deg']))

which returns: 返回:

    Perfect conditions on Saturday at 12 - wind with 13.4 knots and direction: 
    306.511
    Perfect conditions on Saturday at 12 - wind with 14.0 knots and direction: 
    306.001

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

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