如何将列表列表列表转换为具有不均匀列表元素的字典?
我有以下列表:
list_list = [("111", "222", "455"), ("134", "222", "666"), ("465", "364"), ("324", "364")]
我希望第一个元素是值,其余的是字典中的键。我也想拥有一个键的多个值。这是我想要的结果:
{'222': ['111' '134'], '455': ['111'], '666': ['134'], '364': ['465', '324']}
我以以下方式尝试了它,但它行不通。请帮助我
c = {}
for item in list_list:
value = item[0]
for each in range(1, len(item)):
c[item[each]] = value
print(c)
I have the following list:
list_list = [("111", "222", "455"), ("134", "222", "666"), ("465", "364"), ("324", "364")]
I want the first element to be the value and the rest to be the keys in a dictionary. I also want to have multiple values for a key. This is the result that I want:
{'222': ['111' '134'], '455': ['111'], '666': ['134'], '364': ['465', '324']}
I tried it in the following way but it doesn't work. Please help me with it
c = {}
for item in list_list:
value = item[0]
for each in range(1, len(item)):
c[item[each]] = value
print(c)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以这样实现:
对于每个新值,我们检查密钥是否已经存在。就像在解决方案中一样,您覆盖已经具有值的密钥,在这里我们创建列表,或者在可能的情况下附加到现有的列表。
输出 :
You can achieve it this way :
For each new value, we check if the key already exists. As in your solution, you overwrite the keys that already have a value, here we either create the list, or append to the existing one if possible.
Output :