【问题标题】:How to create specific dictionaries from other iterables using for loops?如何使用 for 循环从其他迭代创建特定字典?
【发布时间】:2019-01-04 12:28:09
【问题描述】:

我想使用一个本身也有多个可迭代对象的可迭代对象来创建一个字典。

我试过了:

def setdict(list = ["hello", "world", "something", "foo"])
    for i in list:
        dict = {i[0]:i}
    return dict
print setdict(list = ["hello", "world", "something", "foo"])

我希望输出如下:

{"h":"hello", "w":"world", "s":"something", "f":"foo"}

但实际输出是:

{'f': 'foo'}

【问题讨论】:

    标签: python python-2.7 loops


    【解决方案1】:

    使用dict 理解

    例如:

    def setdict(lst = ["hello", "world", "something", "foo"]):
        return {i[0]:i for i in lst}
    print setdict(lst = ["hello", "world", "something", "foo"])
    

    输出:

    {'h': 'hello', 's': 'something', 'w': 'world', 'f': 'foo'}
    

    在您的情况下,您在每个循环中都覆盖了字典。

    【讨论】:

    • 虽然在这种情况下输入列表没有被修改,但对于初学者来说指出mutable default arguments 也可能是危险的可能会有所帮助
    【解决方案2】:

    这里:

    dict = {i[0]:i}

    您每次都在创建一个新字典。

    先声明再更新:

    result = {}
    for i in items:
        result[i[0]] = i
    return result
    

    另一个答案给出的理解也不错。

    顺便说一句,您不应该使用dict 或list 作为变量名。这是一个内置词,所以你会以神秘的方式破坏你的程序。

    使用列表作为默认参数也会导致awful surprising errors

    【讨论】:

    • 是的,代码不是直接来自我的程序;我知道内置名称不应用作变量名称或参数这一事实。感谢您的回答。
    【解决方案3】:

    您的 for 循环在每次迭代时重新创建整个 dict():dict = {i[0]:i} - 为您留下最后一个值。

    你的(工作)实现会做到这一点

    print setdict(["hello", "world", "something", "foo", "hello - 2"])
    

    到

    {"h":"hello - 2", "w":"world", "s":"something", "f":"foo"}
    

    失去第一个"hello"。


    最好使用默认字典来避免覆盖重复项:

    from collections import defaultdict
    
    def setdict(l): # dont do l = []  - it has ramifications
        d = defaultdict(list)
        for i in l:
            d[i[0]].append(i)
    
        return dict(d)
    
    print setdict(["hello", "world", "something", "foo", "hello - 2"])
    

    输出:

    {'h': ['hello', 'hello - 2'], 's': ['something'], 'w': ['world'], 'f': ['foo']}
    

    其他评论和后果:

    • 不要在内置后调用变量 - 它们会影响它们:

      k = str(5)
      str = 22
      o = str(5)  # crash - the str-function is shadowed
      
    • 避免引用的默认参数:

    def k(l=[]): # reference default param, keeps values
        l.append(0)         # over different calls of the function
            return l 
    
        print(k())
        print(k())
        print(k())
        print(k())
        print(k())
    [0]
    [0, 0]
    [0, 0, 0]
    [0, 0, 0, 0]
    [0, 0, 0, 0, 0]

    见"Least Astonishment" and the Mutable Default Argument

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      相关资源
      最近更新 更多