Good evening, I'm sorry if there is already something similar to my question, but I couldn't find an answer.
I'm trying to deal with values that don't exist in an iteration between the items in a list and the keys in a dictionary.
lista = [1, 2, 3, 4, 5]
dicionario = {"1": {"x": 77.25, "y": 116.330078125},
"2": {"x": 88.25, "y": 126.330078125},
"3": {"x": 99.25, "y": 136.330078125}}
novo_dicionario = {}
for item in lista:
for key, value in dicionario.items():
if str(item) == key:
for v in value.items():
if v[0] in list(novo_dicionario.keys()):
novo_dicionario[v[0]].append(v[1])
else:
novo_dicionario[v[0]] = [v[1]]
Resulting in:
{'x': [77.25, 88.25, 99.25], 'y': [116.330078125, 126.330078125, 136.330078125]}
As you can see, "1, 2, 3" exists as a key in the dictionary. But "4 and 5" does not. So in this case, I'd like my result to handle this exception and look like this:
{'x': [77.25, 88.25, 99.25, 0.00, 0.00], 'y': [116.330078125, 126.330078125, 136.330078125, 0.00, 0.00]}
And as the list grew and was not found as a key in the dictionary, "0.00" was added in the respective amount.
This is what I tried:
for item in lista:
for key, value in dicionario.items():
for v in value.items():
if str(item) == key:
if v[0] in list(novo_dicionario.keys()):
novo_dicionario[v[0]].append(v[1])
else:
novo_dicionario[v[0]] = [v[1]]
else:
for v in value.items():
if v[0] in list(novo_dicionario.keys()):
novo_dicionario[v[0]].append(0.00)
else:
novo_dicionario[v[0]] = [0.00]
But this piece of code adds a lot of 0.00 and not only for each item.
CodePudding user response:
You can easily solve it using defaultdict:
import collections
result = collections.defaultdict(list)
for key in lista:
if str(key) in dicionario:
adict = dicionario[str(key)]
result['x'].append(adict['x'])
result['y'].append(adict['y'])
else:
result['x'].append(0.00)
result['y'].append(0.00)
print(dict(result))
Output:
{'x': [77.25, 88.25, 99.25, 0.0, 0.0], 'y': [116.330078125, 126.330078125, 136.330078125, 0.0, 0.0]}
CodePudding user response:
First, let's get the keys present in each sub-dictionary using set intersection.
from functools import reduce
keys = reduce(set.intersection, (set(d.keys()) for d in dicionario.values()))
# => {'y', 'x'}
Now we can write a dictionary comprehension that makes use of dict.get
to provide default fallbacks for a missing key scenario.
{k: [dicionario.get(str(i), {}).get(k, 0.00) for i in lista] for k in keys}
# => {'y': [116.330078125, 126.330078125, 136.330078125, 0.0, 0.0], 'x': [77.25, 88.25, 99.25, 0.0, 0.0]}