通过索引更改字典的字典键
我有一个字典 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]
有什么想法吗?谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用键列表
key_list = [(99, 14), (33, 16), (12, 99), (11, 99)]
:With a list of keys
key_list = [(99, 14), (33, 16), (12, 99), (11, 99)]
:这是您想要的吗:
{i: value for i, value in enumerate(dico.values())}
Is this what you want:
{i: value for i, value in enumerate(dico.values())}
您无法重命名键。您可以迭代键列表(不是直接),并将键 old 的值插入另一个键下,然后删除 old 一个:
输出之前:
输出之后:
或者您创建一个全新的字典。
You cannot rename keys. You can iterate the list of keys (not directly) and insert the value of key old under another key and delete the old one:
Output before:
Output after:
Or you create a fully new dict from it.
这是一个可能的解决方案:
但是,请记住您是从头开始创建一本新字典。
This is a possible solution:
However, keep in mind that you're creating a new dictionary from scratch.
最简单的解决方案是:
enumerate(dico.values())
相当于zip(range(len(dico)), dico.values())
。将该元组序列传递给 dict() 会创建一个新字典,该字典使用每个元组的第一个元素作为键,使用第二个元素作为值。The simplest solution is:
enumerate(dico.values())
gives you the equivalent ofzip(range(len(dico)), dico.values())
. Passing that sequence of tuples todict()
creates a new dictionary that uses the first element of each tuple as the key and the second element as the value.如果列表中没有这样的组合怎么办?
也许是这样的?:
what about if there is no such combination in the list?
maybe something like this?: