python - 编辑信息有限的嵌套字典

标签 python dictionary

如果我不知道他是驴还是斑马,如何更改'albert'的'空格'?

self.object_attr = {'donkey': {
                              'name': 'roger', 'zone': 'forrest', 'space': [0, 0]}{
                              'name': 'albert', 'zone': 'forrest', 'space': [1, 1]}
                    'zebra': {
                              'name': 'pain', 'zone': 'forrest', 'space': [0, 0]}{
                              'name': 'alesha', 'zone': 'forrest', 'space': [1, 1]}}

print self.object_attr
for species in data.values():
    for animal in species:
        if animal['name'] == 'albert':
            animal['space'] = [50, 50]

#output      this is what object_attr is
{'donkey': {'roger': {'zone': 'forrest', 'space': [0, 0]}, 'albert': {'zone': 'forrest', 'space': [0, 0]}}}


#the error occurs on the "if animal['name'] == 'albert':" line
TypeError: string indices must be integers, not str

最佳答案

首先,您的数据似乎缺少一些标点符号。我对丢失的内容做出了最好的猜测。

data = {'donkey': [{ 'name': 'roger', 'zone': 'forrest', 'space': [0, 0]}, { 'name': 'albert', 'zone': 'forrest', 'space': [1, 1]}],
      'zebra':  [{ 'name': 'roger', 'zone': 'forrest', 'space': [0, 0]}, {'name': 'albert', 'zone': 'forrest', 'space': [1, 1]}]
}

for v in data.values():
    [item.update({'space':[50, 50]}) for item in v if item['name'] == 'albert']

print data

输出

{'donkey': [{'name': 'roger', 'space': [0, 0], 'zone': 'forrest'},
        {'name': 'albert', 'space': [50, 50], 'zone': 'forrest'}],
 'zebra': [{'name': 'roger', 'space': [0, 0], 'zone': 'forrest'},
       {'name': 'albert', 'space': [50, 50], 'zone': 'forrest'}]}

关于python - 编辑信息有限的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10825273/

相关文章:

Java排列3D map

python - 连接两个字典并处理其共同值(value)

python - OpenCV - 检测矩形或五边形

python - 使用 Python 实现 ping

Python,比较和计算列表中的数据

python - 被 flask 阻塞的Gevent甚至使用猴子补丁

Python:如何通过忽略零来绘制二维矩阵的热图?

python - 复杂的字典引用,python

c++ - 另一个奇怪的编译器错误 : calling a templated function which gives undefined referenes

python - 通过 python 和 jinja 获取 json 字典值