Nested dictionary with duplicate keys but different values
I'm having a hard time returning the values of each instance of $t
开发者_开发知识库 in the nested dictionary below. What I need to do is pull each of the key-value pairs and add them individually to another dictionary.
Here's the JSON:
"breed": [
{
"$t": "Chihuahua"
},
{
"$t": "Jack Russell Terrier"
}
]
By the way, I'm using Python 2.7
Something like this?
>>> o = [ { "$t": "Chihuahua" }, { "$t": "Jack Russell Terrier" } ]
>>> [ item["$t"] for item in o ]
['Chihuahua', 'Jack Russell Terrier']
>>>
Is this what you are looking for? (It depends I think on how you want to handle the multiple values corresponding to the same $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 )
This gives you:
{'$t': ['Chihuahua', 'Jack Russell Terrier']}
I don't understood what are you trying to do. If you want to create a Python dict from JSON ans get its values with the "$t" key, here it is (if not, comment and I delete the answer).
# 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"]]
If you need the key-value pairs of every dict inside your dict:
key_and_value_pairs = []
for dic in nested_dict["breed"]:
key_and_value_pairs.extend(dic.items())
精彩评论