如何将列表列表列表转换为具有不均匀列表元素的字典?

发布于 2025-01-24 05:30:51 字数 657 浏览 0 评论 0原文

我有以下列表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦幻的味道 2025-01-31 05:30:51

您可以这样实现:

list_list = [("111", "222", "455"), ("134", "222", "666"), ("465", "364"), ("324", "364")]

c = {}

for item in list_list:

    value = item[0]

    for each in range(1, len(item)):
        if item[each] in c.keys():
            c[item[each]].append(value)
        else:
            c[item[each]] = [value]

print(c)

对于每个新值,我们检查密钥是否已经存在。就像在解决方案中一样,您覆盖已经具有值的密钥,在这里我们创建列表,或者在可能的情况下附加到现有的列表。

输出 :

{'222': ['111', '134'], '455': ['111'], '666': ['134'], '364': ['465', '324']}

You can achieve it this way :

list_list = [("111", "222", "455"), ("134", "222", "666"), ("465", "364"), ("324", "364")]

c = {}

for item in list_list:

    value = item[0]

    for each in range(1, len(item)):
        if item[each] in c.keys():
            c[item[each]].append(value)
        else:
            c[item[each]] = [value]

print(c)

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 :

{'222': ['111', '134'], '455': ['111'], '666': ['134'], '364': ['465', '324']}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文