【问题标题】:how to replace the dictionary key with the available key in the list?如何用列表中的可用键替换字典键?
【发布时间】:2014-03-27 21:36:27
【问题描述】:

我有一个列表列表,其中包含名称及其相关的 uid,如下所示:

 aList = [['x', 'uid1'], ['y', 'uid2'], ['z', 'uid3']]

我有一个这样的字典:

 aDict = {'x': {'a':1}, 'y':{'a':2}, 'z':{'a':7}}

现在如何用 aList 中的相关 uid 替换 aDict 中的键。 输出应该是

  aDict = {'uid1':{'a':1}, 'uid2':{'a':2}, 'uid3':{'a':7}}

【问题讨论】:

    标签: python list dictionary python-2.6


    【解决方案1】:

    首先将aList转换成这样的字典

    aList_dict = dict(aList)
    

    然后使用字典理解,您可以像这样构造新字典

    print {aList_dict.get(k, k):aDict[k] for k in aDict}
    # {'uid2': {'a': 2}, 'uid3': {'a': 7}, 'uid1': {'a': 1}}
    

    aList_dict.get(k, k)表示,如果找到k,则返回对应的值,否则返回k本身。

    注意:即使alist 中没有几个键,此方法也可以工作,因为如果找不到匹配的键,它会将当前键本身作为默认值。

    编辑:由于您使用的是 Python 2.6 和 dictionary comprehensions were not backported to 2.6 from 3.1,您可以使用

    aList_dict = dict(aList)
    print dict((aList_dict.get(k, k), aDict[k]) for k in aDict)
    

    【讨论】:

    • 这在 python 2.6 中有一些问题。它说'for'的语法无效
    • @user2936254 请检查我回答中的编辑部分。
    • 它说 NameError: global name 'aList_dict' is not defined
    • @user2936254 请立即查看。
    • 我已经尝试过了,但它仍然给我一个 NameError
    【解决方案2】:

    迭代aList 并从aDict 中获取值。以value为键复制到结果字典。

    >>> result = {}
    >>> for key, value in aList:
    ...     result[value] = aDict[key]
    ...     
    ... 
    >>> 
    >>> result
    {'uid2': {'a': 2}, 'uid3': {'a': 7}, 'uid1': {'a': 1}}
    

    【讨论】:

      【解决方案3】:

      使用dict comprehension(迭代aList

      >>> {v: aDict[k] for k, v in aList}
      {'uid2': {'a': 2}, 'uid3': {'a': 7}, 'uid1': {'a': 1}}
      

      更新

      如果您不能使用字典理解,请使用dictgenerator expression

      >>> dict((v, aDict[k]) for k, v in aList)
      {'uid2': {'a': 2}, 'uid3': {'a': 7}, 'uid1': {'a': 1}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-17
        • 2022-11-24
        • 1970-01-01
        • 1970-01-01
        • 2018-08-07
        • 1970-01-01
        • 2016-04-14
        • 2018-01-28
        相关资源
        最近更新 更多