【问题标题】:Accessing values in a dictionary访问字典中的值
【发布时间】:2014-11-27 05:04:44
【问题描述】:

这是我的字典:

{'request': [YearCount(year=2005, count=646179), YearCount(year=2006, count=677820), YearCount(year=2007, count=697645), YearCount(year=2008, count= 795265 )], '流浪': [YearCount(year=2005, count=83769), YearCount(year=2006, count=87688), YearCount(year=2007, count=108634), YearCount(year=2008, count= 171015 )], '机场': [YearCount(year=2007, count=175702), YearCount(year=2008, count=173294)]}

我需要帮助弄清楚如何访问 YearCount - 计数值。因为我试图找到每个单词的字母频率,例如“request”、“wandered”和“airport”。我计算总数 输入数据集中所有单词中出现的每个字母。然后这个数字除以总数 所有单词中的字母数。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    如果那是您的字典,那么您可以通过以下方式访问 YearCount 对象列表:

    objects = my_dict['request']
    

    然后您可以遍历列表并访问 .count 值:

    for year_count in objects:
        print(year_count.count)
    

    您还可以将它们相加以获得该单词的总数:

    total = 0
    for year_count in objects:
        total += year_count.count
    print(total)
    

    要显示所有出现的单词,您可以这样做:

    for word, year_counts in my_dict.items():
        total = 0
        for year_count in year_counts:
            total += year_count.count
        print(word, total)
    

    【讨论】:

    • @Adam:在这种情况下,您需要遍历字典中的所有键:for word in my_dict.items():。所以这将是另一个 for 循环中的一个 for 循环。请参阅我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多