久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

合并字典,保留重復鍵的值

Merge dictionaries retaining values for duplicate keys(合并字典,保留重復鍵的值)
本文介紹了合并字典,保留重復鍵的值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

給定 n 個字典,編寫一個函數,該函數將返回一個唯一字典,其中包含重復鍵的值列表.

Given n dictionaries, write a function that will return a unique dictionary with a list of values for duplicate keys.

例子:

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'b': 4}
d3 = {'a': 5, 'd': 6}

結果:

>>> newdict
{'c': 3, 'd': 6, 'a': [1, 5], 'b': [2, 4]}

到目前為止我的代碼:

>>> def merge_dicts(*dicts):
...     x = []
...     for item in dicts:
...         x.append(item)
...     return x
...
>>> merge_dicts(d1, d2, d3)
[{'a': 1, 'b': 2}, {'c': 3, 'b': 4}, {'a': 5, 'd': 6}]

生成一個為這些重復鍵生成一個值列表的新字典的最佳方法是什么?

What would be the best way to produce a new dictionary that yields a list of values for those duplicate keys?

推薦答案

def merge_dicts(*dicts):
    d = {}
    for dict in dicts:
        for key in dict:
            try:
                d[key].append(dict[key])
            except KeyError:
                d[key] = [dict[key]]
    return d

這會返回:

{'a': [1, 5], 'b': [2, 4], 'c': [3], 'd': [6]}

這個問題略有不同.這里所有的字典值都是列表.如果長度為 1 的列表不希望這樣做,則添加:

There is a slight difference to the question. Here all dictionary values are lists. If that is not to be desired for lists of length 1, then add:

    for key in d:
        if len(d[key]) == 1:
            d[key] = d[key][0]

return d 語句之前.但是,我真的無法想象您何時想要刪除該列表.(考慮將列表作為值的情況;然后刪除項目周圍的列表會導致模棱兩可的情況.)

before the return d statement. However, I cannot really imagine when you would want to remove the list. (Consider the situation where you have lists as values; then removing the list around the items leads to ambiguous situations.)

這篇關于合并字典,保留重復鍵的值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 四虎永久 | 欧美日韩在线成人 | 国产精品亚洲一区 | www.av在线| 国产在线一区观看 | 国产综合精品一区二区三区 | 久久国产精品精品国产色婷婷 | 日韩视频一区二区三区 | 国产欧美日韩久久久 | 狠狠爱免费视频 | 黄网站免费在线看 | 亚洲精品国产综合区久久久久久久 | 天天射影院 | 国产精品一区在线 | www312aⅴ欧美在线看 | 国产视频一区二区三区四区五区 | 欧美精品1区2区3区 免费黄篇 | 国产99热| 国产一区二区三区免费观看在线 | 日本一区二区不卡 | 日本久久一区 | 国产精品久久久久久福利一牛影视 | 日韩精品视频在线免费观看 | 国产区视频在线观看 | 在线播放国产一区二区三区 | 亚洲国产精品99久久久久久久久 | 国产精品亚洲一区 | a a毛片 | 欧美美女爱爱视频 | 午夜精 | 亚洲丝袜天堂 | 欧美精品在线一区 | 国产一区二区三区久久 | 91n成人| 日韩免费中文字幕 | 国产三区视频在线观看 | 欧美专区在线 | 国产一区二区三区免费观看在线 | 国产成人a亚洲精品 | 在线亚洲人成电影网站色www | 人人澡视频 |