【问题标题】:Changing dict structure from values to keys将字典结构从值更改为键
【发布时间】:2020-07-06 01:28:28
【问题描述】:

假设我有以下字典:

my_dict = {'month': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 'year': [2006, 2012, 2003, 2006, 2012, 2018, 2020, 2011, 2000, 2001, 2013, 2013]}

我怎样才能创建一个像这样的新字典?

new_dict = {'1': '2006', '2': '2012', ..., '12': '2013'}

【问题讨论】:

    标签: python dataframe dictionary for-loop key-value-store


    【解决方案1】:
    dict(zip(my_dict['month'], my_dict['year']))
    

    转换为字符串值:

    months = [str(item) for item in my_dict['month']]
    years = [str(item) for item in my_dict['year']]
    dict(zip(months, years))
    

    【讨论】:

    • 如果只是技术性问题,OP 似乎要求提供字符串作为输出,而不是 int
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    相关资源
    最近更新 更多