【问题标题】:delete specific keys from a dictionary based on a condition根据条件从字典中删除特定键
【发布时间】:2022-01-18 20:46:42
【问题描述】:

我有一本像下面这样的字典:

   {'weather1': {428: 68253},
     'weather2': {1323: 68586, 1343: 68605, 1344: 68606},
     'weather3': {311: 68183, 312: 68184, 290: 68164},
     'weather4': {699: 68304, 721: 68323, 722: 68324},
     'weather5': {7260: 69942},
     'weather6': {15: 68095, 35: 68114, 36: 68115})

我想删除只有一个值的键。比如我想删除weather1weather5,把字典的其余部分恢复成字典格式

有什么想法吗?

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    假设d 输入。使用简单的字典理解:

    out = {k:v for k,v in d.items() if len(v)>1}
    

    输出:

    {'weather2': {1323: 68586, 1343: 68605, 1344: 68606},
     'weather3': {311: 68183, 312: 68184, 290: 68164},
     'weather4': {699: 68304, 721: 68323, 722: 68324},
     'weather6': {15: 68095, 35: 68114, 36: 68115}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      相关资源
      最近更新 更多