我正在寻找一种动态方法来解决我的问题。我有一个非常复杂的结构,但为简单起见,
我有这样的字典结构:
dict1={
"outer_key1" : {
"total" : 5 #1.I want the value of "total"
},
"outer_key2" :
[{
"type": "ABC", #2. I want to count whole structure where type="ABC"
"comments": {
"nested_comment":[
{
"key":"value",
"id": 1
},
{
"key":"value",
"id": 2
}
] # 3. Count Dict inside this list.
}}]}
我想要这个迭代字典并解决#1,#2和#3。
我尝试解决#1和#3:
def getTotal(dict1):
#for solving #1
for key,val in dict1.iteritems():
val = dict1[key]
if isinstance(val, dict):
for k1 in val:
if k1=='total':
total=val[k1]
print total #gives output 5
#for solving #3
if isinstance(val,list):
print len(val[0]['comment']['nested_comment']) #gives output 2
#How can i get this dynamicallty?
输出:
total=5
2
Que 1:什么是pythonic方法来获得" nested_comment"下的字典总数。清单?
问题2:如何获得type =" ABC"的类型总数。 (注意:type是" outer_key2")下的嵌套键。
答案 0 :(得分:0)
Que 1:什么是pythonic方法来获得" nested_comment"下的字典总数。列表?
标准库中的用户Counter
。
from collections import Counter
my_list = [{'hello': 'world'}, {'foo': 'bar'}, 1, 2, 'hello']
dict_count = Counter([x for x in my_list if type(x) is dict])
Que 2:如何获得type =" ABC"的类型总数。 (注意:type是" outer_key2")下的嵌套键。
目前尚不清楚你在这里要求的是什么。如果按"总计数",则表示所有词组中的注释总数,其中"键入"等于" ABC":
abcs = [x for x in dict1['outer_key2'] if x['type'] == 'ABC']
comment_count = sum([len(x['comments']['nested_comment']) for x in abcs])
但我必须说,这是你正在处理的一些奇怪的数据。
答案 1 :(得分:0)
你得到#1和#3的答案,检查一下
...
allowNull: false,
...
假设下面是outer_key2的数据结构,这就是你获得from collections import Counter
dict1={
"outer_key1" : {
"total" : 5 #1.I want the value of "total"
},
"outer_key2" :
[{
"type": "ABC", #2. I want to count whole structure where type="ABC"
"comments": {
"nested_comment":[
{
"key":"value",
"key": "value"
},
{
"key":"value",
"id": 2
}
] # 3. Count Dict inside this list.
}}]}
print "total: ",dict1['outer_key1']['total']
print "No of nested comments: ", len(dict1['outer_key2'][0]['comments'] ['nested_comment']),
的评论总数的方法
type='ABC'