【问题标题】:How to switch the value of different keys inside a dicitonary? [duplicate]如何在字典中切换不同键的值? [复制]
【发布时间】:2018-10-24 23:01:47
【问题描述】:

给定这样的字典:

{'Fruit': 'PAR',
'Brand': 'best',
'date': 'imorgon',
'type': 'true',
'class': 'Good',
'time': '2018-10-25',
'number': 234}

如何将与一个键关联的值替换为另一个键的值?比如我想在日期值中删除和替换,时间的值:

{'Fruit': 'PAR',
'Brand': 'best',
'date': '2018-10-25',      <----- HERE
'type': 'true',
'class': 'Good',
                           <----- This one is removed and replaced into the data key
'number': 234}

我尝试过:

{value : key for key,value in a.items()}

然而它只是切换键的值。

【问题讨论】:

    标签: python python-3.x dictionary list-comprehension


    【解决方案1】:

    你可以使用正常的赋值和弹出:

    data = {'Fruit': 'PAR',
    'Brand': 'best',
    'date': 'imorgon',
    'type': 'true',
    'class': 'Good',
    'time': '2018-10-25',
    'number': 234}
    
    data['date'] = data.pop('time')
    
    print(data)
    

    输出

    {'date': '2018-10-25', 'type': 'true', 'number': 234, 'Fruit': 'PAR', 'class': 'Good', 'Brand': 'best'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 2019-06-17
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      相关资源
      最近更新 更多