我有一個字典dico,我用這段代碼創建了它:
dico = {}
for index, row in data.iterrows():
tup = (row['OsId'], row['BrowserId'])
if tup not in dico:
dico[tup] = []
dico[tup].append(row['PageId'])
[print(f"{key} : {value}") for key, value in dico.items()]
這里是一個 dico 樣本:
combination : list of pages :
(99, 14) : [789615, 1158132, 789615, 789615, 1109643, 789615, 1184903]
(33, 16) : [955761, 955764, 955767, 955761, 955764, 955764, 1154705, 955761]
(12, 99) : [1068379, 1184903, 955764, 955761, 1184903, 955764]
(11, 99) : [1187774]
我正在尋找一種方法來更改 dico 以通過組合串列中的索引替換組合值
例如我有組合串列:(99, 14), (33, 16), (12, 99), (11, 99)
預期的結果應該是:
0 : [789615, 1158132, 789615, 789615, 1109643, 789615, 1184903]
1 : [955761, 955764, 955767, 955761, 955764, 955764, 1154705, 955761]
2 : [1068379, 1184903, 955764, 955761, 1184903, 955764]
3 : [1187774]
有什么想法嗎?謝謝
uj5u.com熱心網友回復:
帶有鍵串列key_list = [(99, 14), (33, 16), (12, 99), (11, 99)]:
dict(enumerate(dico[k] for k in key_list))
uj5u.com熱心網友回復:
這是你想要的嗎:
{i: value for i, value in enumerate(dico.values())}
uj5u.com熱心網友回復:
您不能重命名密鑰。您可以迭代鍵串列(不直接)并將鍵old的值插入另一個鍵并洗掉舊鍵:
keys = (99, 14), (33, 16), (12, 99), (11, 99)
d = {}
# iterates the LIST of keys, not dict.keys - that would not work
for idx, k in enumerate(keys,1):
d[k] = 1111*idx
# before
print(d)
for idx,old in enumerate(keys):
d[idx] = d[old] # copy value
del d[old] # delete old key from dict
# after
print(d)
之前的輸出:
{(99, 14): 1111,
(33, 16): 2222,
(12, 99): 3333,
(11, 99): 4444}
輸出后:
{0: 1111,
1: 2222,
2: 3333,
3: 4444}
或者您從中創建一個全新的字典。
uj5u.com熱心網友回復:
這是一個可能的解決方案:
dico = dict(zip(range(len(dico)), dico.values()))
但是,請記住,您是從頭開始創建新詞典。
uj5u.com熱心網友回復:
最簡單的解決方案是:
dico = dict(enumerate(dico.values()))
enumerate(dico.values())給你相當于zip(range(len(dico)), dico.values()). 將該元組序列傳遞給dict()創建一個新字典,該字典使用每個元組的第一個元素作為鍵,第二個元素作為值。
uj5u.com熱心網友回復:
用組合串列中的索引替換組合值
如果串列中沒有這樣的組合怎么辦?也許是這樣的?:
comb_list = [(99, 14), (33, 16), (12, 99), (11, 99)]
dico = {(99, 14) : [789615, 1158132, 789615, 789615, 1109643, 789615, 1184903],
(33, 16) : [955761, 955764, 955767, 955761, 955764, 955764, 1154705, 955761],
(12, 99) : [1068379, 1184903, 955764, 955761, 1184903, 955764],
(11, 99) : [1187774],
(77, 77) : [7777777]} # not in the list
dico = {comb_list.index(k) if k in comb_list else k:v for k,v in dico.items()}
print(dico)
'''
{0: [789615, 1158132, 789615, 789615, 1109643, 789615, 1184903],
1: [955761, 955764, 955767, 955761, 955764, 955764, 1154705, 955761],
2: [1068379, 1184903, 955764, 955761, 1184903, 955764],
3: [1187774],
(77, 77): [7777777]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438554.html
標籤:Python python-3.x 字典
下一篇:Python中的字典任務:選舉
