[Python] Why doesn't a python dict.update() return the object?

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have this code:

    award_dict = {
    "url": "http://facebook.com",
    "imageurl": "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
    "count": 1,
    }

    def award(name, count, points, desc_string, my_size, parent):
    if my_size > count:
    a = {
    "name": name,
    "description": desc_string % count,
    "points": points,
    "parent_award": parent,
    }
    a.update(award_dict)
    return self.add_award(a, siteAlias, alias).award


    But the code felt rather cumbersome. I would have preferred to be able to write:

    def award(name, count, points, desc_string, my_size, parent):
    if my_size > count:
    return self.add_award({
    "name": name,
    "description": desc_string % count,
    "points": points,
    "parent_award": parent,
    }.update(award_dict), siteAlias, alias).award


    Why doesn't the update method return the original dictionary, so as to allow chaining, like how it works in JQuery? Why isn't it acceptable in python?


    See How do I merge two dictionaries in a single expression in Python? for workarounds.

    Continue reading...

Compartilhe esta Página