使用python,通过从列表中提取key:value来创建字典

时间:2020-01-17 14:26:38

标签: python datetime dictionary

我需要从list1制作两个字典:

        <ListBox Name="lbTodoList" HorizontalContentAlignment="Stretch" 
             IsHitTestVisible="False" AlternationCount="2">
        <ListBox.ItemTemplate>
            <DataTemplate>
                    <TextBlock x:Name="LabelSourceCode" Text="{Binding TextItem}" 
                               Height="Auto" Width="Auto" 
                               FontFamily="Verdana"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我能够从以前发布的问题的答复中获得帮助。

list1 = [['8/16/2016 9:55', 6], ['11/22/2015 13:43', 29], ['5/2/2016 10:14', 1],
['8/2/2016 14:20', 3], ['10/15/2015 16:38', 17], ['9/26/2015 23:23', 1],
['4/22/2016 12:24', 4], ['11/16/2015 9:22', 1], ['2/24/2016 17:57', 1], 
['6/4/2016 17:17', 2]]

count_by_hour = {} # this is created by extracting the hour from index[0] of list1

输出:

for each in list1:
   if each[0].split(':')[0][-2] == " ": #split by : to get second last char and check if >9
   hours.append(each[0].split(':')[0][-1:]) # if hour is <9 take last char which is hour
else:
   hours.append(each[0].split(':')[0][-2:]) #else take last 2 chars
print('Hour extracted:')
print(hours)

现在,我该怎么做:

Counts by hour:
{'9': 2, '13': 1, '10': 1, '14': 1, '16': 1, '23': 1, '12': 1, '17': 2}

一如既往,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

请注意,我们需要为多个类别(小时)中的每个类别分别累计总和。一个简单的解决方案(在纯Python中)结合了累加器模式,同时使用字典来存储所有计数。

首先,让我们使用Query(table, hk='1234', sk='1#Apple') Query(table, hk='1234', sk='1#Banana') Query(table, hk='1234', sk='1#Cherry') 通过列表理解来提取小时数。

Query(table, hk='1234', sk BEGINS WITH '1#')

解决方案是使用字典来累积每个类别的统计信息。通过(a)以空字典开头和(b)更新每个新值的总和来执行此操作。这可以通过以下方式完成。

time.strptime

请注意,In [1]: list1 = [['8/16/2016 9:55', 6], ['11/22/2015 13:43', 29], ['5/2/2016 10:14', 1], : ['8/2/2016 14:20', 3], ['10/15/2015 16:38', 17], ['9/26/2015 23:23', 1], : ['4/22/2016 12:24', 4], ['11/16/2015 9:22', 1], ['2/24/2016 17:57', 1], : ['6/4/2016 17:17', 2]] In [2]: from time import strptime In [3]: hour_list = [(strptime(time, "%m/%d/%Y %H:%M").tm_hour, val) for time, val in list1] 用于获取该小时的当前值(如果存在),否则,则使用默认值0。