heres my dict:
{
1: { 'A': u'Eggs',
'B': 1400,
'C': u'Jibber',
'D': u'355'},
2: { 'A': u'Avocados',
'B': 1000,
'C': u'Jabber',
'D': u'356'},
..}
Template.mustache
{{#each}}
<li><strong>{{A}}</strong></li>
<li><strong>{{B}}</strong></li>
...
{{/each}}
{{#empty}}
<p>The list is empty.</p>
{{/empty}}
If the variable is called data, how do I iterate over its items if they are only identifiable by index?
Related
Lets say I have this dict:
dictos = {
"a": {
"b": {
"c": 3,
"d": 4,
"e": [],
"f": [{"g": 5}, 'test', {"h": 6, "i": 7}]
}
}
}
And lets say I want to delete "c": 3 pair. What I am doing:
import dpath.util
path = "a/b/c"
dpath.util.delete(dictos, path)
It is working great. The output is:
{
'a': {
'b': {
'd': 4,
'e': [],
'f': [{'g': 5}, 'test', {'h': 6, 'i': 7}]
}
}
}
The problem is when I am trying to delete key:value pair inside the list.
Lets say I want to delete "h":6. So when doing:
path = "a/b/f[2]/h"
dpath.util.delete(dictos, path)
I am getting:
dpath.exceptions.PathNotFound: Could not find a/b/f[2]/h to delete
it.
So the question basically is how to delete items from nested dicts that are in a list?
It seems the library expects the same separator to be used for all segments i.e. use a/b/f/2/h
path = "a/b/f/2/h"
dpath.util.delete(dictos, path)
print(dictos)
Result:
{'a': {'b': {'d': 4, 'e': [], 'f': [{'g': 5}, 'test', {'i': 7}]}}}
I have this trie dictionary:
{'s': {'h': {'o': {'w': {'value': 'a programm'},
'o': {'t': {'value':'a bullet'}},
'e': {'value': 's.th to wear'}},
'a': {'m': {'e': {'value': 'a feeling'}}},
'i': {'t': {'value': 'deficate'}}}}}
I want to define a function that searches through this trie dict and finds its values.
how to do it ?
here is how I do it:
def finder(dict_trie,word):
if word:
first,rest = word[0],word[1:]
finder(dict_trie[first],rest)
else:
print(dict_trie["value"])
finder(dict_trie,"shit")
result = deficate
I have a nested dictionary that looks like below,
{
'product_list.show_date': "May '21",
'product_list.new_users':
{
'product_list.product':
{
'A': None,
'B': 377,
'C': None,
'D': 67,
'E': None,
'F': 1,
'G': None
}
}
}
And I want to clear it out in a way that parent keys are not there. So basically, I want a dictionary that is not nested. Like below,
{
'product_list.show_date': "May '21",
'A': None,
'B': 377,
'C': None,
'D': 67,
'E': None,
'F': 1,
'G': None
}
I am using the recursive function to do this, but it's not 100% correct.
Here's my code,
def clear_nd(d, nested_dict):
for key in nested_dict:
if type(nested_dict[key]) != dict:
d[key] = nested_dict[key]
elif type(nested_dict[key]) == dict:
nested_dict = nested_dict[key]
clear_nd(d, nested_dict)
return d
d = {}
clear_nd(d, nested_dict)
For below example,
nested_dict = {
'product_list.show_date': "May '21",
'product_list.new_users': {
'product_list.product': {
'A': None,
'B': 377,
'C': None,
'D': 67,
'E': None,
'F': 1,
'G': None
},
'prod.product': {
'Alk': None,
'Bay': 377,
'Lent': None,
'R': 67,
'Ter': None,
'Wi': 1,
'e': None
}
},
'duct_list.new_users': {
'pdust.product': {
'H': None,
'y': 377,
'nt': None,
'C': 67,
'sfer': None,
's': 1,
'le': None
}
}
}
Does Pandas or any other library has a way to do this. Structure of the nested dictionary is dynamic so we won't know how deep it is. And Keys will also change, so we won't able to know beforehand what are the keys in the dictionary. Any help will be appreciated. Thanks!!
If you allow the lower level tag labels to take prefixes of higher level tag labels, you can use the Pandas function pandas.json_normalize, which handles nested dict and turn it into a flat table Pandas dataframe.
Then, use pandas.DataFrame.to_dict to turn the Pandas dataframe to a dict. For example,
import pandas as pd
d = {
'product_list.show_date': "May '21",
'product_list.new_users':
{
'product_list.product':
{
'A': None,
'B': 377,
'C': None,
'D': 67,
'E': None,
'F': 1,
'G': None
}
}
}
pd.json_normalize(d).to_dict('records')[0]
Result:
{'product_list.show_date': "May '21",
'product_list.new_users.product_list.product.A': None,
'product_list.new_users.product_list.product.B': 377,
'product_list.new_users.product_list.product.C': None,
'product_list.new_users.product_list.product.D': 67,
'product_list.new_users.product_list.product.E': None,
'product_list.new_users.product_list.product.F': 1,
'product_list.new_users.product_list.product.G': None}
I have a input request which consists of multiple dictionaries with similar keys and values as dictionaries.
Here's the input I have.
req = {"main1":
{"x": {"a":220},"y": {"b":66}},
"main2":
{"x": {"c":"1000","d":"copper"},
"y": {"c":"1200","d":"Copper"}}}
Output I need:
{'cable1': {'a': 220, 'c': '1000', 'd': 'copper'}, 'cable2': {'b': 66, 'c': '1200', 'd': 'Copper'}}
Here's the try i made:
actual_req = []
for attr1, attr2 in req.items():
for j, k in attr2.items():
actual_req.append(k)
actual_req[0].update(actual_req[2])
actual_req[1].update(actual_req[3])
data = {'cable1': actual_req[0], 'cable2': actual_req[1]}
print(data)
I just need the more generic way of writing in short. It should also handle input with
req = {"main1":
{"x": {"a":220},"y": {"b":66}},
"main2":
{"x": {"c":"1000","d":"cooper"},
"y": {"c":"1200","d":"Copper"}},
"main3":
{"x": {"e":20},"y": {"f":6}}}
Just update final dictionary as you go through values of original dictionary:
req = {"main1":
{"x": {"a":220},"y": {"b":66}},
"main2":
{"x": {"c":"1000","d":"copper"},
"y": {"c":"1200","d":"Copper"}}}
final_dict = {'cable1': {}, 'cable2': {}}
for v in req.values():
final_dict['cable1'].update(v['x'])
final_dict['cable2'].update(v['y'])
Final dict would look like this:
{'cable1': {'a': 220, 'c': '1000', 'd': 'copper'}, 'cable2': {'b': 66, 'c': '1200', 'd': 'Copper'}}
I have this json with different levels:
[{'A': 1, 'B': 2, 'CA': {'CA1': '3', 'CA23': '4'}},
{'A': 1, 'B': {'CA1': '3'}, 'CA': {'CA1': '3', 'CA23': '4'}}]
And I want to get only the values for each row using list comprehension:
The expected result is:
[[1, 2, '3', '4'], [1, '3', '3', '4']]
Without using list comprehension this code work:
values = []
for row in json:
rows = []
for item in row.items():
if str(row[item[0]]).startswith("{"):
temp = row[item[0]].values()
else:
temp = [row[item[0]]]
rows.extend(temp)
values.append(rows)
Some ideas?
Here's a way to do it that cheats a little by using an auxiliary helper function to flatten the nested dictionary objects comprising each "row" of your data-structure.
import json # For pretty-printing data and results.
from collections.abc import MutableMapping
def flatten(nested):
''' Yield values from nested dictionary data structure. '''
for value in nested.values():
if isinstance(value, MutableMapping): # Nested?
yield from flatten(value)
else:
yield value
json_values = [{'A': 1, 'B': 2, 'CA': {'CA1': '3', 'CA23': '4'}},
{'A': 1, 'B': {'CA1': '3'}, 'CA': {'CA1': '3', 'CA23': '4'}}]
print('Before:')
print(json.dumps(json_values, indent=4))
# Here's the list comprehension.
result = [list(flatten(nested)) for nested in json_values]
print()
print('After:')
print(json.dumps(result, indent=4))
Output:
Before:
[
{
"A": 1,
"B": 2,
"CA": {
"CA1": "3",
"CA23": "4"
}
},
{
"A": 1,
"B": {
"CA1": "3"
},
"CA": {
"CA1": "3",
"CA23": "4"
}
}
]
After:
[
[
1,
2,
"3",
"4"
],
[
1,
"3",
"3",
"4"
]
]