使用Python将数组转换为字典内的单个值

时间:2017-03-11 05:10:27

标签: python arrays json

我在python中有这个字典:

example = {
    "foo": ["1"],
    "bar": ["1","2"]
}

如何有效地转换并使用Python变量示例:

example = {
    "foo": "1",
    "bar": ["1","2"]
}

1 个答案:

答案 0 :(得分:0)

假设dict没有嵌套,你可以迭代dict来修改它:( Python 3,见here差异)

for key, value in example.items():
  if isinstance(value, list) and len(value) == 1:
    example[key] = value[0]