使用递归来查找嵌套dict的值和dict的返回键

时间:2018-01-26 20:36:00

标签: python python-3.x dictionary

我有一个练习,其中生日词典如下:

    birthdays = 
    {"Anne": {"month":"Jan","day":"27"},
    "Mike":{"month":"Feb","day":"13"},
    "Nicolas":{"month":"Jun","day":14}, 
    "Marta": {"month":"Jan","day":16}}

问题是定义一个函数,在给定一个月的情况下,打印一份包含该月份生日的所有人的列表,以及日期。

这是我到目前为止所得到的:

    def birthbymonth(book, month):
        for k,v in book.items():
            if isinstance(v, dict):
                birthbymonth(v,month)           
            else:
                if month == v:
                    print(book)

当称为birthbymonth(生日,“Jan”)打印时:

    {'month': 'Jan', 'day': '27'}
    {'month': 'Jan', 'day': 16}

然而,我不知道如何打印那些有生日的人的名字。

4 个答案:

答案 0 :(得分:5)

我在这里没有看到任何使用递归的理由。

def birthbymonth(book, month):
    for person,birthday in book.items():
        if birthday['month'] == month:
            print('{}: {} {}'.format(person, birthday['month'], birthday['day']))

答案 1 :(得分:1)

正如其他人所指出的那样,不需要递归。相反,使用列表理解:

birthdays = {"Anne": {"month":"Jan","day":"27"},
"Mike":{"month":"Feb","day":"13"},
"Nicolas":{"month":"Jun","day":14}, 
"Marta": {"month":"Jan","day":16}}
def dates(birthdays, month):
   return ["{}: {}".format(a, b['day']) for a, b in birthdays.items() if b['month'] == month]

print(dates(birthdays, 'Jan'))

输出:

['Marta: 16', 'Anne: 27']

答案 2 :(得分:1)

如果您真的想使用递归(不推荐用于此问题),您可以对现有代码进行一些修改:

birthdays = {
    "Anne": {"month":"Jan","day":27},
    "Mike": {"month":"Feb","day":13},
    "Nicolas": {"month":"Jun","day":14},
    "Marta": {"month":"Jan","day":16}
}

def birthbymonth(book, month):
    names = []
    for k,v in book.items():
        if isinstance(v, dict):
            names += [(k, book[k]["day"])] if birthbymonth(v,month) is True else []
        else:
            if month == v:
                return True
    return names

print(birthbymonth(birthdays, 'Jan'))
#[('Marta', 16), ('Anne', 27)]

答案 3 :(得分:1)

这是一个解决方案:

birthdays = {"Anne": {"month":"Jan","day":"27"},
             "Mike": {"month":"Feb","day":"13"},
             "Nicolas": {"month":"Jun","day":14}, 
             "Marta": {"month":"Jan","day":16}}

{k: v['day'] for k, v in birthdays.items() if v['month']=='Jan'}

# {'Anne': '27', 'Marta': 16}