[英]How can I create a dict with keys that contain multiple values from two lists?
[英]Dict from two lists including multiple values for keys
是否可以從兩個具有相同鍵的列表中創建一個字典, 而不重復整個數據集?
最小示例:
keys = [1, 2, 3, 2, 3, 4, 5, 1]
values = [1, 2, 3, 4, 5, 6, 7, 8]
# hoped for result:
dictionary = dict(???)
dictionary = {1 : [1,8], 2:[2,4], 3:[3,5], 4:[6], 5:[7]}
使用zip
,插入的鍵值對將覆蓋舊的鍵值對:
dictionary = dict(zip(keys,values))
dictionary = {1: 8, 2: 4, 3: 5, 4: 6, 5: 7}
我對Multidict也很滿意。
這是一種不需要2 for循環的方法
h = defaultdict(list)
for k, v in zip(keys, values):
h[k].append(v)
print(h)
# defaultdict(<class 'list'>, {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]})
print(dict(h))
# {1: [1, 8], 2: [2, 4], 3: [3, 5], 4: [6], 5: [7]}
這是我唯一能做的。
dictionary = {k: [values[i] for i in [j for j, x in enumerate(keys) if x == k]] for k in set(keys)}
它遠非易讀。 請記住,清晰的代碼總是比偽智能代碼更好;)
我認為這是一個易於理解的示例。 不幸的是,它沒有像您希望的那樣使用zip
,也沒有避免迭代,因為這樣的任務必須涉及某種形式的迭代。
# Your data
keys = [1, 2, 3, 2, 3, 4, 5, 1]
values = [1, 2, 3, 4, 5, 6, 7, 8]
# Make result dict
result = {}
for x in range(1, max(keys)+1):
result[x] = []
# Populate result dict
for index, num in enumerate(keys):
result[num].append(values[index])
# Print result
print(result)
如果您知道keys
數組中值的范圍,則可以通過將results
字典作為帶有整數鍵和空列表值的文字提供, results
加快此過程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.