JarochoEngineer
JarochoEngineer

Reputation: 1787

Update list in dictionary if key not present in list

I am trying to find the best approach to update the values of the dictionary including the key when this (key) is not present in the value.

I proceeded as follows:

        for key, value in m_dict.items():
            if key not in value:
                m_list = m_dict.get(key)
                m_list.append(key)
                m_dict[key] = m_list

That works, but I can see it is a bit lengthy. Can I update the values including they key when this is not present in a better way?

Thanks for sharing

Upvotes: 0

Views: 26

Answers (1)

cajomar
cajomar

Reputation: 488

Just do this:

for key, value in m_dict.items():
    if key not in value:
        # At this point, `value`, `m_dict.get(key)`, and `m_dict[key]` are the same list
        value.append(key)

Upvotes: 1

Related Questions