简体   繁体   English

有没有办法在字典中索引嵌套列表? PYTHON

[英]Is there a way to index a nested list inside a dictionary? PYTHON

I have a dictionary like such:我有一本这样的字典:

dict = {"TestA" : [[1,2,3],[4,5,6]], "TestB" : [[7,8,9],[10,11,12]]}

When I try to run the code ahead to create a single line string, I get an error ValueError: too many values to unpack (expected 2)当我尝试提前运行代码以创建单行字符串时,出现错误 ValueError: too many values to unpack (expected 2)

key, val = list(dict.items())[0][0]
cooltest = str(key) + str (val)

I sort of understand why I get the error (because there are 2 "variables" expected, which are key and value, and instead it gets more than 2).我有点理解为什么我会收到错误(因为预期有 2 个“变量”,它们是键和值,而不是超过 2 个)。 However, as seen, I have indexed to the integer 1, so my val should be 1 and my key should be TestA.但是,如所见,我已经索引到 integer 1,所以我的 val 应该是 1,我的 key 应该是 TestA。 Is it even possible to index a nested list that's inside a dictionary?甚至可以索引字典内的嵌套列表吗? Thank you for your time and your advice, in advance!提前感谢您的时间和建议!

Edit: Solution is to just use two different methods (.keys and.values) rather than just using.items编辑:解决方案是只使用两种不同的方法(.keys 和.values),而不仅仅是使用.items

First of all following code gives me an error.首先,以下代码给了我一个错误。

dict = {TestA : [1,2,3],[4,5,6], TestB : [7,8,9],[10,11,12]}

I'll assume what you have wanted is我假设你想要的是

dict = {"TestA": [[1,2,3],[4,5,6]], "TestB": [[7,8,9],[10,11,12]]}

Also, list(dict.items()) is equal to [('TestA', [[1, 2, 3], [4, 5, 6]]), ('TestB', [[7, 8, 9], [10, 11, 12]])] .此外, list(dict.items())等于[('TestA', [[1, 2, 3], [4, 5, 6]]), ('TestB', [[7, 8, 9], [10, 11, 12]])] Therefore, list(dict.items())[0][0] is a string, which would cause a error in your code.因此, list(dict.items())[0][0]是一个字符串,这会导致您的代码出错。 It is likely what you want is list(dict.items())[0][1] which is equal to [[1, 2, 3], [4, 5, 6]] .您可能想要的是list(dict.items())[0][1] ,它等于[[1, 2, 3], [4, 5, 6]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM