Python dictionaries-How to keep the new value from overwriting the previous value?

前端 未结 4 622
孤独总比滥情好
孤独总比滥情好 2020-12-21 10:02

I want to create a Dictionary called \"First\" (as in First Name) that will store numerous first names which are all stored in the dictionary via a function. The idea is th

4条回答
  •  伪装坚强ぢ
    2020-12-21 10:25

    Python < 2.5 doesn't have defaultdict, however you can achieve the same thing in with ordinary dict too.

    >>> names = {}
    >>> name_list = [('Jon', 'Skeet'), ('Jeff', 'Atwood'), ('Joel', 'Spolsky')]
    >>> for first, last in name_list:
            names.setdefault('first', []).append(first)
            names.setdefault('last', []).append(last)
    >>> print names
    {'first': ['Jon', 'Jeff', 'Joel'], 'last': ['Skeet', 'Atwood', 'Spolsky']}
    

    setdefault returns the existing value if the key already exists in dict, or sets the new value and returns the newly set value if the key doesn't exist.

提交回复
热议问题