I may have not written the best of codes, but let's say I have a dictionary within a dictionary which output looks like this:
print node
> {
> 0: {'NODE': 'CLOUDY', 'GATE': 'EQUAL', 'PROB': 0.5},
> 1: {'NODE': 'RAIN', 'CPT_1': 0.2, 'CPT_0': 0.8, 'GATE': 'OR', 'PROB': 0.5, 'PNODE_0': 'Cloudy'},
> 2: {'NODE': 'SPRINKLER', 'CPT_1': 0.9, 'CPT_0': 0.5, 'GATE': 'OR', 'PROB': 0.7, 'PNODE_0': 'Cloudy'},
> 3: {'NODE': 'WETGRASS', 'CPT_3': 0.01, 'CPT_2': 0.1, 'CPT_1': 0.1, 'CPT_0': 1.0, 'GATE': 'OR', 'PROB': 0.5, 'PNODE_0': 'Rain', 'PNODE_1': 'Sprinkler'}
> }
I want to see the final result of:
print string
> ['CLOUDY', 'RAIN', 'SPRINKLER', 'WETGRASS']
So far, I have written this to get an output exactly as the one above.
string = "["
for value in xrange (0, len(node)):
string += "'" + node[value].get("NODE") + "', "
string = string[:-2]
string += "]"
print string
I was wrapping my head around extracting all values from a dictionary within a dictionary that has a key of "NODE". Is that possible?
Just use the values from the dict:
print([d["NODE"] for d in node.values()])
['CLOUDY', 'RAIN', 'SPRINKLER', 'WETGRASS']
If the key might not be in all dicts just use in
to check first:
print([d["NODE"] for d in node.values() if "NODE" in d])
node.values()
is going to give you all the dicts:
[{'NODE': 'CLOUDY', 'GATE': 'EQUAL', 'PROB': 0.5}, {'NODE': 'RAIN', 'CPT_1': 0.2, 'CPT_0': 0.8, 'GATE': 'OR', 'PROB': 0.5, 'PNODE_0': 'Cloudy'}, {'NODE': 'SPRINKLER', 'CPT_1': 0.9, 'CPT_0': 0.5, 'GATE': 'OR', 'PROB': 0.7, 'PNODE_0': 'Cloudy'}, {'NODE': 'WETGRASS', 'CPT_3': 0.01, 'CPT_1': 0.1, 'CPT_0': 1.0, 'CPT_2': 0.1, 'GATE': 'OR', 'PROB': 0.5, 'PNODE_0': 'Rain', 'PNODE_1': 'Sprinkler'}]
So you just extract from each.
If you actually want to form a string that looks like a list:
s = "[{}]".format(",".join([d["NODE"] for d in node.values() if "NODE" in d]))
Or simple:
print(str([d["NODE"] for d in node.values() if "NODE" in d]))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments