具有重复键但具有不同值的嵌套字典

时间:2011-07-30 18:58:00

标签: python json dictionary

我很难在下面的嵌套字典中返回$t的每个实例的值。我需要做的是拉出每个键值对并将它们分别添加到另一个字典中。

这是JSON:

"breed": [
            {
                "$t": "Chihuahua"
            },
            {
                "$t": "Jack Russell Terrier"
            }
         ]

顺便说一下,我正在使用Python 2.7

3 个答案:

答案 0 :(得分:1)

这样的东西?

>>> o = [ { "$t": "Chihuahua" }, { "$t": "Jack Russell Terrier" } ]
>>> [ item["$t"] for item in o ]
['Chihuahua', 'Jack Russell Terrier']
>>>

答案 1 :(得分:0)

这是你在找什么? (这取决于我想你如何处理对应于同一$t的多个值。)

nestedDict = { "breed": [
                        {
                         "$t": "Chihuahua"
                         },
                         {
                          "$t": "Jack Russell Terrier"
                          }
                         ]
              }

dictEntries = [ (k, v) for dicList in nestedDict.values() for d in dicList for (k, v) in d.items() ]

flattenedDict = { }
for k, v in dictEntries:
    flattenedDict.setdefault( k, [] ).append( v )

print ( flattenedDict )

这会给你:

{'$t': ['Chihuahua', 'Jack Russell Terrier']}

答案 2 :(得分:0)

我不明白你想做什么。如果你想从JSON创建一个Python dict,用“$ t”键获取它的值,这里是(如果不是,注释,我删除答案)。

# Many thanks to Dogbert, whose answer I copied the list comprehension from 
# (changing a few things), and many thanks to slothrop, whose answer gave me 
# ideas for my variable name. Not for those people, I would have used a silly 
# name like `thing` and would have used a for loop.
import json

nested_dict = json.loads('{"breed": [{"$t": "Chihuahua"}, '
                                    '{"$t": "Jack Russell Terrier"}]}')
[dic["$t"] for dic in nested_dict["breed"]]

如果你需要你词典中每个词典的键值对:

key_and_value_pairs = []
for dic in nested_dict["breed"]:
    key_and_value_pairs.extend(dic.items())