【问题标题】:Looking for a key in a nested dict to change the type of the key在嵌套字典中查找键以更改键的类型
【发布时间】:2019-08-22 20:12:47
【问题描述】:

我有一个这样的字典:

exampleDict={'name': 'Example1', 'code': 2, 'price': 23, 'dimensions': [2,2]}

我想把dimensions的类型改成一个字符串,像这样:

exampleDict['dimensions'] = str(dict['dimensions'])

这很好用。但是想象一下我的exampleDict 中有嵌套的字典,而dimensions 在里面有点远。

我的猜测是递归地做一些事情。从我在这里搜索的内容来看,(例如this onethis one,他们在递归函数中使用yield,但我不确定为什么要使用它。

我正在考虑这样做:

def changeToStringDim(d):
    if 'dimensions' in d:
        d['dimensiones'] = str(d['dimensions'])
    for k in d:
        if isinstance(d[k], list):
            for i in d[k]:
                for j in changeToStringDim(i):
                    j[dimensions] = str(j['dimensions'])

我在这里找到了它,但不是分配j[dimensions]=str(j['dimensions']),而是分配了yield。但我对此进行了调整,它在像这个例子这样的字典中运行良好。

现在我正试图在一个嵌套中做到这一点。

exDict2={'name': 'example1',
         'nesting': {'subnesting1': 'sub2',
                     'coordinates': [41.6769705, 2.288154]},
         'price': 123123132}
         }

使用相同的功能,但将其更改为坐标:

def changeToStringCoord(d):
    if 'coordinates' in d:
        d['coordinates'] = str(d['coordinates'])
    for k in d:
        if isinstance(d[k], list):
            for i in d[k]:
                for j in changeToStringDim(i):
                    j['coordinates'] = str(j['coordinates'])

它不会做任何事情。我已经调试过了,它只会通过namenestingpriceisinstance 工作不正常(或者工作正常,但我不完全理解它的方法)。

【问题讨论】:

  • 为什么不只是像d[k] = str(d[k]) 这样的东西?显示您想要的输出,因为目前您的描述令人困惑。
  • 当然,我会立即编辑问题。但不是这样,因为我可以从参数接收字典。它可以在普通字典中包含coordinates,也可以嵌套。所以我不知道我得到了什么字典!只有我需要改变它! @meowgoesthedog
  • 是的,但它不起作用。更改 dict 将导致 string indeces must be integersin isinstance(d[k], dict) @meowgoesthedog 出现错误
  • isinstance 需要一个类型,可以是listdict 等等。我没有覆盖任何东西!它需要一个类型! @meowgoesthedog

标签: python dictionary


【解决方案1】:

带有 cmets 的代码:

def changeNestedListToString(d):
    for k in d:

        # recursive call on dictionary type
        if isinstance(d[k], dict):
            changeNestedListToString(d[k])

        # convert lists to string
        elif isinstance(d[k], list):
            d[k] = str(d[k])

        # leave everything else untouched

测试数据:

example = {
    'name': 'example1',
    'nesting': {
        'subnesting1': 'sub2',
        'coordinates': [41.6769705, 2.288154]
    },
    'price': 123123132
}

调用函数后:

{
    'price': 123123132, 
    'name': 'example1', 
    'nesting': {
         'coordinates': '[41.6769705, 2.288154]', 
         'subnesting1': 'sub2'
    }
}

如您所见,'coordinates' 已转换为字符串,而其他所有内容都保持不变。

【讨论】:

  • 坐标是如何变化的,不是别的,如果在函数中,价值'coordinates'不会出现!但它正在工作!
  • @M.K 它只是将list 类型的所有值转换为字符串。如果您只想更改特定键,则应传递所述键的列表。
  • 这比我实际想要的还要好。所有类型的字符串列表都是完美的!谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-04-14
  • 2017-12-05
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2018-05-23
相关资源
最近更新 更多