Hello everyone,
I’m trying to search for a specific key in a deeply nested dict which can also contain arrays.
In a first step I import a yaml file which I parse using YAML.jl. This gives me a nested dict.
If we take the truncated example of the README file from the YAML.jl package:
# data.yml
receipt: Oz-Ware Purchase Invoice
date: 2012-08-06
customer:
given: Dorothy
family: Gale
This would be parsed as
julia> using YAML
julia> data = YAML.load(open("data.yml"))
Dict{Any,Any} with 3 entries:
"receipt" => "Oz-Ware Purchase Invoice"
"customer" => Dict{Any,Any}(Pair{Any,Any}("given", "Dorothy"),Pair{Any,Any}("…
"date" => 2012-08-06
How would I access in for instance the value of the “given” form the dict corresponding to “customer”?
I would like to achieve this in a general way, where there could be multiple levels of nesting.
I tried to translate the following python code which I found on StackExchange:
def retrieve_nested_value(mapping, key_of_interest):
mappings = [mapping]
while mappings:
mapping = mappings.pop()
try:
items = mapping.items()
except AttributeError:
# we didn't store a mapping earlier on so just skip that value
continue
for key, value in items:
if key == key_of_interest:
yield value
else:
# type of the value will be checked in the next loop
mappings.append(value)
where mapping
is a dict.
This is my attempt to translate it to julia
function retreive_nested_value(dict, key_of_interest)
dictv = [dict]
while isempty(dictv) == false
dict = pop!(dictv)
for (key,value) in dict
if key == key_of_interest
return value
else
dictv = [dictv , [value]]
end
end
end
end
But unfortunately, it gives me only the values of the first level (same as get(dict, key_of_interest,0)). I cannot fetch the values of the lower levels.
How would one do this in julia?
Many thanks in advance,
Olivier