如何阅读带有列表的字典?

时间:2016-02-09 19:47:47

标签: python list dictionary

如何读取字典中的列表并尝试将字符串数字更改为数字?例如:

obj = {'azul':'4','rojo':[{'rojo_a':'1','rojo_b':'2'}],'amarillo':'xxx','naranja':[{'naranja_1':'1','naranja_2':'2'}]}

我用它来将字典数字字符串更改为整数:

{k:int(v) if v.isdigit() else v for k,v in obj.items()}

但它不起作用,所以我尝试这样的事情:

for objs in obj:
if objs.isdigit():
    k:int(v)
else:
    for k,v in objs.items():
        print k

但这也失败了。

2 个答案:

答案 0 :(得分:4)

这似乎是递归的好问题

obj = {'azul':'4','rojo':[{'rojo_a':'1','rojo_b':'2'}],'amarillo':'xxx','naranja':[{'naranja_1':'1','naranja_2':'2'}]}
def fix_ints(obj):
    if isinstance(obj,basestring):
        try:
            return int(obj)
        except ValueError:
            print "I cant Make %r an int"%obj
            return obj
    elif isinstance(obj,(list,tuple)):
        return [fix_ints(item) for item in obj]
    elif isinstance(obj,dict):
        return dict((key,fix_ints(value)) for key,value in obj.items())
    else:
        print "I have no idea what to do with %r"%obj

new_obj = fix_ints(obj)
print new_obj

请注意,python不支持尾递归,所以如果这个数据结构非常深(嵌套级别大于1k),那么递归可能不合适......

粗糙你也可以用它做愚蠢的字符串技巧

import json,re
new_obj = json.loads(re.sub("\"(\d+)\"","\\1",json.dumps(obj)))

(虽然你应该像我在我的第一个例子中那样做...这第二种方法真的只是为了好玩)

答案 1 :(得分:0)

字符串到数字:

def int_it(obj):
    if obj.isdigit():
        obj = int(obj)

    return obj

Dict to number(无论嵌套dicts或列表的数量):

class Convert(object):
    def __init__(self, obj):
        self.obj = obj

        if isinstance(obj, dict):
            self.handle_dict(obj)

    def handle_dict(self, obj):
        for key, value in obj.items():
            if isinstance(value, str) and value.isdigit():
                self.obj[key] = int_it(value)

            elif isinstance(obj[key], list):
                ins = HandleList(obj[key])
                self.obj[key] = ins.obj

            elif isinstance(obj[key], dict):
                ins = Convert(obj.items())
                self.obj[key] = ins.obj

        return obj

列出数字,无论嵌套列表或数字的数量如何。

class HandleList(object):
    def __init__(self, obj):
        self.obj = obj
        self.handle_list(obj)

    def handle_list(self, obj):
        for index, item in enumerate(obj):
            if isinstance(item, list):
                obj.index(index, [HandleList(val).obj for val in item])

            elif isinstance(item, str):
                obj.index(index, int_it(item))

            elif isinstance(item, dict):
                Convert(item)

        return obj


output = Convert(values)

print(output.obj)

返回:

{
   'amarillo': 'xxx', 
   'naranja': [{'naranja_1': 1, 'naranja_2': 2}], 
   'rojo': [{'rojo_b': 2, 'rojo_a': 1}], 
   'azul': 4
 }

鉴于输入:

values = {
   'azul':'4',
   'rojo': [
            {'rojo_a':'1',
             'rojo_b':'2'
            }
           ],
   'amarillo':'xxx',
   'naranja': [
               {'naranja_1':'1',
                'naranja_2':'2'
               }
              ]
   }