我在列表list indices must be integers, not str
的迭代过程中收到错误meters_info
。为什么我会收到这样的错误?
谢谢大家指出我,原始应用程序在 django ,我正在将其转换为烧瓶应用程序。在django,他们是datastructures.SortedDict
。我如何在烧瓶中使用相同的功能
See this link
from django.utils import datastructures
meters_info = datastructures.SortedDict([
("instance", {
'label': '',
'description': _("Existence of instance"),
}),
("instance:<type>", {
'label': '',
'description': _("Existence of instance <type> "
"(openstack types)"),
}),
("memory", {
'label': '',
'description': _("Volume of RAM"),
}),])
Flask App
def _get_nova_meters_info(self):
meters_info= [
("instance", {
'label': '',
'description': "Existence of instance",
}),
("instance:<type>", {
'label': '',
'description': "Existence of instance <type> (openstack types)",
}),
("memory", {
'label': '',
'description': "Volume of RAM",
}),]
在控制台中收到消息
File "/home/vagrant/api/ceilometer.py", line 137, in _get_nova_meters_info
meters_info[name]=dict(meters_info["instance:<type>"])
TypeError: list indices must be integers, not str
请参阅以下我收到错误的方法
for flavor in self.get_flavor_names():
name='instance:%s' %flavor
meters_info[name]=dict(meters_info["instance:<type>"])
meters_info[name]['description']= (
'Duration of instance type %s (openstack flavor)' % flavor)
return meters_info
def get_flavor_names(self):
return ['m1.tiny', 'm1.small', 'm1.medium', 'm1.large', 'm1.nano','m1.xlarge', 'm1.micro']
答案 0 :(得分:2)
您有一个包含词典的元组列表。无法使用字符串访问,您需要使用整数。最初的Django应用程序使用了一种名为SortedDict
的特殊类型的Django字典,幸好Python自2.7以来就有一个等价的OrderedDict
。你只需要像这样导入它
from collections import OrderedDict
然后调整语法以使用OrderedDict
并删除值周围的_()
:
meters_info = OrderedDict([
("instance", {
'label': '',
'description': "Existence of instance",
}),
("instance:<type>", {
'label': '',
'description': "Existence of instance <type> "
"(openstack types)",
}),
("memory", {
'label': '',
'description': "Volume of RAM",
}),])
答案 1 :(得分:1)
要以这种方式使用数据,您需要将meter_info重建为字典:
meters_info= {
"instance" : {
'label': '',
'description': "Existence of instance",
},
"instance:<type>" : {
'label': '',
'description': "Existence of instance <type> (openstack types)",
},
"memory" : {
'label': '',
'description': "Volume of RAM",
},}
如果你有相同的结构来使用类,它也会更好。例如
class Meters_info_param_stucture(object):
def __init__(self, label = None, description = None):
self.label = label
self.description = description
meters_info= {
"instance" : Meters_info_param_stucture(description = "Existence of instance"),
"instance:<type>" : Meters_info_param_stucture(description = "Existence of instance <type> (openstack types)"),
"memory" : Meters_info_param_stucture(description = "Volume of RAM"),}
>>>meters_info["memory"].description
'Volume of RAM'
答案 2 :(得分:0)
问题是您的数组是list
tuple
个,而tuple
有str
作为第一个元素,而dict
是meters_info[0][0][<some_key>]
第二。所以你应该像这样访问它:
meters_info[0][0]["instance"]
例如:
meters_info
但是我不明白你保持这种结构和原因。您应该考虑将bitwise_and
重组为字典,例如Dmitry.Samborskyi suggests。