![](/img/trans.png)
[英]Creating a dict containing a sub-dict as the new value with the index as the key
[英]create a sub-dict with first element in dict for every key
我有一個包含不同列表的字典,我需要一種快速有效的方法來創建一個包含相同鍵的新字典(如果我可以獨立於鍵名更好)和列表的一個值讓我們說第 i 個
一個例子
someDict = {'key1': [1,2,3,4,5],'otherkey': [.256,.221,.487,.454,.555]}
那么第一個元素(i = 0)應該返回
subdict = {'key1':1,'otherkey':0.256}
第三個要素是:
subdict = {'key1':3,'otherkey':0.487}
我可以for key,val in someDict...
做一些來創建新的 dict 但我不確定這是最好的選擇
根據您需要新dict
對象的用途,pandas dataframe 可能是最佳選擇。 對於類似表的操作,它通常會更高效。 例如,如果您打算將這些 dicts 放在一個列表中,那么 datatrame 可能是一個很好的選擇。
>>> import pandas as pd
>>> someDict = {'key1': [1,2,3,4,5],'otherkey': [.256,.221,.487,.454,.555]}
>>> df = pd.DataFrame(someDict)
>>> df
key1 otherkey
0 1 0.256
1 2 0.221
2 3 0.487
3 4 0.454
4 5 0.555
嘗試這個:
def ith_val_subdict(input_dict, i):
return {k: v[i] for k, v in input_dict.items()}
例子:
someDict = {'key1': [1,2,3,4,5],'otherkey': [.256,.221,.487,.454,.555]}
subdict_0 = ith_val_subdict(someDict, 0)
print(subdict_0)
# {'key1': 1, 'otherkey': 0.256}
subdict_2 = ith_val_subdict(someDict, 2)
print(subdict_2)
# {'key1': 3, 'otherkey': 0.487}
您可以在列表理解中使用兩個zip
:
[dict(zip(someDict, vals)) for vals in zip(*someDict.values())]
output:
[{'key1': 1, 'otherkey': 0.256},
{'key1': 2, 'otherkey': 0.221},
{'key1': 3, 'otherkey': 0.487},
{'key1': 4, 'otherkey': 0.454},
{'key1': 5, 'otherkey': 0.555}]
注意。 這會將值截斷為最短子列表的長度,如果長度不均勻並且需要填充,請使用itertools.zip_longest
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.