使用set
,sorted
將兩個列表合併爲一個並排序:
>>> a1 = {u'2016-03-11': [u'20:00', u'22:10']}
>>> a2 = {u'2016-03-11': [u'20:00', u'23:10'],u'2016-03-12': [u'20:00', u'22:10']}
>>> an = {}
>>> for d in a1, a2:
... for key in d:
... an[key] = sorted(set(an.get(key, []) + d[key]))
... # ^^ Merge two lists (dictionary values) into one, and sort
...
>>> print an
{u'2016-03-11': [u'20:00', u'22:10', u'23:10'],
u'2016-03-12': [u'20:00', u'22:10']}
UPDATE
使用字典解析
替代版本(假設合併只有兩個詞典):
>>> {key: sorted(set(a1.get(key,[]) + a2.get(key,[]))) for key in set(a1)|set(a2)}
{u'2016-03-11': [u'20:00', u'22:10', u'23:10'],
u'2016-03-12': [u'20:00', u'22:10']}
'sorted(list(v))''可以簡化爲'sorted(v)' – falsetru
@falsetru,修正,謝謝。 –