简体   繁体   English

遍历字典 python

[英]Iterating through a dictionary python

I am trying to write a test for a function, and create a fake dictionary to use in the test - however, I cannot work out what the format of the dictionary should be for it to work in the function.我正在尝试为 function 编写测试,并创建一个假字典以在测试中使用 - 但是,我无法确定字典的格式应该是什么才能在 function 中工作。 The function goes like this: function 是这样的:

...

for data in form.cleaned_data["flows"]:
    data_point = property.MeterPoint.objects.get(id=data["id"])

I thought that the dictionary should be in the following format:我认为字典应该采用以下格式:

form.cleaned_data = {'flows': {"id": "1234"}}

but I keep getting this error when running the test:但我在运行测试时不断收到此错误:

    id=data["id"]
E   TypeError: string indices must be integers

When iterating over a dict, you get their key and not their value.当迭代一个 dict 时,你会得到它们的键而不是它们的值。 Which means to access the value we have to use variable[key], you were trying, to access the key, like a dict, since the key is a string, python was assuming you tried to access a char of the string, but this can only be done with an int.这意味着要访问我们必须使用变量 [key] 的值,您正在尝试访问密钥,就像一个 dict,因为密钥是一个字符串,python 假设您尝试访问字符串的一个字符,但是这个只能用 int 来完成。

for key in form.cleaned_data["flows"]:
    data_point = property.MeterPoint.objects.get(id=form.cleaned_data["flows"][key]["id"])

I am not sure what framework you are using but what I can say is that if我不确定您使用的是什么框架,但我可以说的是,如果

form.cleaned_data["flow"]

is the dictionary you defined as是您定义为的字典

{"id": "1234"}

then your data variable has a type of str (string).那么您的数据变量的类型为str (字符串)。 Because looping over a dictionary is looping over the keys of dictionary.因为遍历字典就是遍历字典的键。 If you want to loop over values you can use .values() method eg如果你想遍历值,你可以使用.values()方法,例如

for data in my_dict.values():
    print(data)

If you use .values() then your data would be of type str (string) and have a value of "1234" .如果您使用.values()那么您的数据将是str (字符串)类型并且值为"1234"

Moreover you can loop over a tuple of (pair of) key-value items.此外,您可以遍历(一对)键值项的元组。 for this purpose you can use .items() method.为此,您可以使用.items()方法。 eg例如

for key, value in my_dict.items():
    print(key, value)
  • Note about tuple unpacking: If you have a tuple such as t = (1, 2, 3) you can assign it into three variables as a, b, c = t .关于元组拆包的注意事项:如果您有一个元组,例如t = (1, 2, 3)您可以将其分配给三个变量,即a, b, c = t With this you have a = 1, b = 2, c = 3 .有了这个,你有a = 1, b = 2, c = 3

Some note about the error: The error you are faceing is because type of data is probably str and for accessing index of a string you should pass an int (integer) value not a string.关于错误的一些注意事项:您面临的错误是因为data类型可能是str并且要访问字符串的索引,您应该传递一个int (整数)值而不是字符串。

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

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