【问题标题】:Reset new keys to a dictionary将新键重置为字典
【发布时间】:2016-08-24 14:35:36
【问题描述】:

我有一本 python 字典。

A=[0:'dog',1:'cat',3:'fly',4,'fish',6:'lizard']

我想根据range(len(A))(自然增量)重置键,应该是这样的:

new_A=[0:'dog',1:'cat',2:'fly',3:'fish',4:'lizard']

我该怎么做?

【问题讨论】:

  • 字典使用花括号而不是方括号
  • @vaultah 但这不会保留值的相对顺序,对吗?
  • 带有 0-4 键的字典也可能只是一个列表。

标签: python dictionary key


【解决方案1】:

以下是 py2.x 和 py3.x 的工作示例:

A = {0: 'dog', 1: 'cat', 3: 'fly', 4: 'fish', 6: 'lizard'}

B = {i: v for i, v in enumerate(A.values())}
print(B)

【讨论】:

  • @vaultah A.values() 的顺序是准随机的,只是因为你得到{0:'dog',1:'cat',2:'fly',3:'fish',4:'lizard'},一旦你不能假设它总是那个顺序——这就是我正确的意思。我认为确定性排序很重要。
  • @janbrohl 我不知道你在说什么,先看看问题在问什么
  • 在完整阅读问题时,您会看到结果应该类似于 {0:'dog',1:'cat',2:'fly',3:'fish',4:'lizard'},这恰好保持了键的相同排序顺序。
  • janbrohl 是对的,python dicts 不强制执行特定顺序。在 pypy 上,dicts 是默认排序的,所以当项目没有以“正确的顺序”插入时它会中断。
【解决方案2】:

如果要按旧键的升序分配新键,则

new_A = {i: A[k] for i, k in enumerate(sorted(A.keys()))}

【讨论】:

    【解决方案3】:

    如果你想保持相同的键顺序

    A={0:'dog',1:'cat',3:'fly',4,'fish',6:'lizard'}
    new_A=dict((i,A[k]) for i,k in enumerate(sorted(A.keys()))
    

    【讨论】:

      【解决方案4】:

      字典没有排序。如果您的键是增量整数,您不妨使用列表。

      new_A = list(A.values())

      【讨论】:

        【解决方案5】:

        如果您想通过创建排序以及通过密钥访问,那么您需要OrderedDict

        >>> from collections import OrderedDict
        >>> d=OrderedDict()
        >>> d['Cat'] = 'cool'
        >>> d['Dog'] = 'best'
        >>> d['Fish'] = 'cold'
        >>> d['Norwegian Blue'] = 'ex-parrot'
        >>> d
        OrderedDict([('Cat', 'cool'), ('Dog', 'best'), ('Fish', 'cold'), ('Norwegian Blue', 'ex-parrot')])
         >>> d.values()
        odict_values(['cool', 'best', 'cold', 'ex-parrot'])
        >>> d.keys()
        odict_keys(['Cat', 'Dog', 'Fish', 'Norwegian Blue'])
        

        您保留按添加顺序以序列形式访问项目的能力,但您还可以通过 dict(哈希)为您提供快速的按键访问。如果你想要“自然”的序列号,你可以正常使用enumerate

        >>> for i,it in enumerate( d.items()): 
        ...   print( '%5d %15s %15s' % ( i,it[0], it[1]) )
        ... 
            0             Cat            cool
            1             Dog            best
            2            Fish            cold
            3  Norwegian Blue       ex-parrot
        >>>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-17
          • 1970-01-01
          • 1970-01-01
          • 2012-12-10
          • 2020-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多