I have dicts like this :
list_dicts = [
{
'code': 'A1', 'name': 'White',
},
{
'code': 'A2', 'name': 'Black',
},
{
'code': 'A1', 'name': 'White',
},
{
'code': 'A3', 'name': 'Red',
}
]
And how to get dicts look like this from above dicts ?
list_dicts = [
{
'code': 'A1', 'name': 'White', 'qty': 2
},
{
'code': 'A2', 'name': 'Black', 'qty': 1
},
{
'code': 'A3', 'name': 'Red', 'qty': 1
}
]
..........................
Assuming that you actually have a list of dicts:
list_dict = [
{'code': 'A1', 'name': 'White'},
{'code': 'A2', 'name': 'Black'},
{'code': 'A1', 'name': 'White'},
{'code': 'A3', 'name': 'Red'}
]
Then you can use collections.Counter to count the values:
In []:
from collections import Counter
Counter((x['code'], x['name']) for x in list_dict)
Out[]:
Counter({('A1', 'White'): 2, ('A2', 'Black'): 1, ('A3', 'Red'): 1})
It's a fairly easy exercise to turn this back into the list of dictionaries you are looking for.
Just use a defaultdict to store the counts of each (code, name):
from collections import defaultdict
list_dict = [{'code': 'A1', 'name': 'White'},
{'code': 'A2', 'name': 'Black'},
{'code': 'A1', 'name': 'White'},
{'code': 'A3', 'name': 'Red'},
]
d = defaultdict(int)
for dic in list_dict:
key = dic['code'], dic['name']
d[key] += 1
>>> print(dict(d))
{('A1', 'White'): 2, ('A2', 'Black'): 1, ('A3', 'Red'): 1}
Then just create a new list, and insert the new data from the dictionary above:
new_dict_list = [{'code':code, 'name':name, 'qty':qty} for (name, code), qty in d.items()]
>>> print(new_dict_list)
[{'code': 'A1', 'name': 'White', 'qty': 2}, {'code': 'A2', 'name': 'Black', 'qty': 1}, {'code': 'A3', 'name': 'Red', 'qty': 1}]
Related
My data is below
food ID
name
ingredients
ingredient ID
amount
unit
1
rice
red
R1
10
g
1
soup
blue
B1
20
g
1
soup
yellow
Y1
30
g
and I want to convert it like this
{
'data': [
{
'name': 'rice',
'ingredients': [
{
'name': 'red',
'ingredient_id':'R1',
'amount': 10,
'unit': 'g',
}
]
},
{
'name': 'soup',
'ingredients': [
{
'name': 'blue',
'ingredient_id':'B1',
'amount': 20,
'unit': 'g',
},
{
'name': 'yellow',
'ingredient_id':'Y1',
'amount': 30,
'unit': 'g',
}
]
}
]
}
How can I do it? Do I need to use the same library as pandas?
Yes you can modify your data by using custom code function inside python.
For your required format you need to use this code for format your data into json.
import pandas as pd
data = [[1, 'rice', 'red', 'R1', 10, 'g'],
[1, 'soup', 'blue', 'B1', 20, 'g'],
[1, 'soup', 'yellow', 'Y1', 30, 'g'],
[1, 'apple', 'yellow', 'Y1', 30, 'g']]
df = pd.DataFrame(data, columns=['food ID', 'name', 'ingredients', 'ingredient ID', 'amount', 'unit'])
def convert_data_group(group):
ingredients = [{'name': row['ingredients'], 'ingredient_id': row['ingredient ID'], 'amount': row['amount'], 'unit': row['unit']} for _, row in group.iterrows()]
return {'name': group.iloc[0]['name'], 'ingredients': ingredients}
unique_names = df['name'].unique().tolist()
result = []
for name in unique_names:
group = df[df['name'] == name]
result.append(convert_data_group(group))
final_result = {'datas': result}
print(final_result)
Your final result will be:
{'datas': [{'name': 'rice', 'ingredients': [{'name': 'red', 'ingredient_id': 'R1', 'amount': 10, 'unit': 'g'}]}, {'name': 'soup', 'ingredients': [{'name': 'blue', 'ingredient_id': 'B1', 'amount': 20, 'unit': 'g'}, {'name': 'yellow', 'ingredient_id': 'Y1', 'amount': 30, 'unit': 'g'}]}, {'name': 'apple', 'ingredients': [{'name': 'yellow', 'ingredient_id': 'Y1', 'amount': 30, 'unit': 'g'}]}]}
I got this dictionary:
[{'id': 1, 'code': 'a'},
{'id': 2, 'code': 'b'},
{'id': 3, 'code': 'c'}]
and I want to change it to:
[{ 1: 'a'},
{2: 'b'},
{ 3: 'c'}]
(python pandas)
a = [{'id': 1, 'code': 'a'},
{'id': 2, 'code': 'b'},
{'id': 3, 'code': 'c'}]
b = []
for dic in a:
b.append({dic['id'] : dic['code']})
print(b)
>>[{1: 'a'}, {2: 'b'}, {3: 'c'}]
One option is with a dictionary comprehension:
[{ent['id']: ent['code']} for ent in a]
[{1: 'a'}, {2: 'b'}, {3: 'c'}]
I have a dictionary like this:
dic = {'features': [{'type': 'Feature',
'geometry': {'geodesic': False,
'type': 'Point',
'coordinates': [33.44904857310912, 52.340950190985474]},
'id': '0',
'properties': {'a1': 1.313,
'a2': -0.028, 'a3': 0.0026, 'a4': -0.025...
'a40': -0.056 ...
{'type': 'Feature',
'geometry': {'geodesic': False,
'type': 'Point',
'coordinates': [33.817042613128294, 52.340950190985474]},
'id': '1',
'properties': {'a1': 1.319,
'a2': -0.026, 'a3': 0.003,'a4': -0.045, ...
'a40': -0.032 ......
Almost 1000 ids, e.g. 'id': '0', 'id': '1'...'id': '960'
I want to iterate through the dictionary to extract a list of element containing 'a1', 'a2'... 'a40', separately. Something like this:
list_a1 = [1.313, 1.319... ]
list_a2 = [-0.028, -0.026 ...]
How to get these lists using Python?
You can use something like this. Using setdefault makes it dynamic and any number of keys in properties will be included in the result.
dic = {'features': [{'type': 'Feature',
'geometry': {'geodesic': False,
'type': 'Point',
'coordinates': [33.44904857310912, 52.340950190985474]},
'id': '0',
'properties': {'a1': 1.313,
'a2': -0.028,
'a3': 0.0026,
'a4': -0.025,
'a40': -0.056}},
{'type': 'Feature',
'geometry': {'geodesic': False,
'type': 'Point',
'coordinates': [33.817042613128294, 52.340950190985474]},
'id': '1',
'properties': {'a1': 1.319,
'a2': -0.026,
'a3': 0.003,
'a4': -0.045,
'a40': -0.032}}]}
separated_properties = {}
for feature in dic['features']:
for key, val in feature['properties'].items():
separated_properties.setdefault(key, []).append(val)
print(separated_properties)
print('a1: ', separated_properties['a1'])
Output
{'a1': [1.313, 1.319],
'a2': [-0.028, -0.026],
'a3': [0.0026, 0.003],
'a4': [-0.025, -0.045],
'a40': [-0.056, -0.032]}
a1: [1.313, 1.319]
I've got a nested dictionary like that:
d={'a1': {'b': ['x', 1]}, 'a2': {'b1': ['x1', 2]}}
Expected result:
[
{
"measurements": "XXXXX",
"tags": {
"MPC": b,
"host": a1
},
"time": "timexxxxx",
"fields": {
x: 1
}
},
{
"measurements": "XXXXX",
"tags": {
"MPC": b,
"host": a2
},
"time": "timexxxxx",
"fields": {
x: 1
}
}
]
that is what I'm trying, however it's being overwritten
for k,v in d.items():
metrics['measurements'] = "XXXXX"
if isinstance(v,dict):
for j,h in v.items():
metrics['tags'] = {'MPC':j,'host':k}
metrics['time'] = "timexxxxx"
for value in h:
metrics['fields'] = {j:h}
and I'm getting:
{'fields': {'b1': ['x1', 2]},
'measurements': 'XXXXX',
'tags': {'MPC': 'b1', 'host': 'a2'},
'time': 'timexxxxx'}
Could you give me some pointers on how to deal with this?
Thanks
see below
import pprint
d = {'a1': {'b': ['x', 1]}, 'a2': {'b1': ['x1', 2]}}
data = []
for k, v in d.items():
entry = {"measurements": "XXXXX"}
entry['tags'] = {'MPC': list(v.keys())[0],"host": k}
entry["time"] = "timexxxxx"
values= list(v.values())
entry["fields"] = {values[0][0]:values[0][1]}
data.append(entry)
pprint.pprint(data)
output
[{'fields': {'x': 1},
'measurements': 'XXXXX',
'tags': {'MPC': 'b', 'host': 'a1'},
'time': 'timexxxxx'},
{'fields': {'x1': 2},
'measurements': 'XXXXX',
'tags': {'MPC': 'b1', 'host': 'a2'},
'time': 'timexxxxx'}]
This code can help you:
d={'a1': {'b': ['x', 1]}, 'a2': {'b1': ['x1', 2]}}
def convert(dictionary):
return [
{
"measurements": "XXXXX",
"tags": {
"MPC": list(value.keys())[0],
"host": key
},
"time": "timexxxxx",
"fields": dict(value.values())
} for key, value in dictionary.items()
]
print(convert(d))
Results in [{'measurements': 'XXXXX', 'tags': {'MPC': 'b', 'host': 'a1'}, 'time': 'timexxxxx', 'fields': {'x': 1}}, {'measurements': 'XXXXX', 'tags': {'MPC': 'b1', 'host': 'a2'}, 'time': 'timexxxxx', 'fields': {'x1': 2}}]
You can do it like this
#Empty List
li=[]
#Add Items in list
for i in range(2):
d = {}
d["measurment"] = "XXXXX"
d["tags"] = {1: "x"}
d["time"] = "timexxx"
d["field"] = {2: "y"}
li.append(d)
#Print list elements
for i in li:
for key, value in i.items():
print(key, ":", value)
print()
How do I convert the following defaultdict()?
defaultdict(<class 'dict'>, {
'key1_A': {
'id': 'key1',
'length': '663',
'type': 'A'},
'key1_B': {
'id': 'key1',
'length': '389',
'type': 'B'},
'key2_A': {
'id': 'key2',
'length': '865',
'type': 'A'},
'key2_B': {
'id': 'key2',
'length': '553',
'type': 'B' ........}})
the value of the id i.e key1 becomes the key, and the key called length is changed to length_A or B with corresponding values belonging in the earlier type.
defaultdict(<class 'dict'>, {
'key1': {
'length_A': '663',
'length_B': '389'},
'key2': {
'length_A': '865',
'length_B': '553'}})
Thanks,
I think this does what you want:
from collections import defaultdict
import pprint
d = {
'key1_A': {
'id': 'key1',
'length': '663',
'type': 'A',
},
'key1_B': {
'id': 'key1',
'length': '389',
'type': 'B',
},
'key2_A': {
'id': 'key2',
'length': '865',
'type': 'A',
},
'key2_B': {
'id': 'key2',
'length': '553',
'type': 'B',
},
}
transformed = defaultdict(dict)
for v in d.values():
transformed[v["id"]]["length_{}".format(v["type"])] = v["length"]
pprint.pprint(transformed)
# Output:
# defaultdict(<class 'dict'>,
# {'key1': {'length_A': '663', 'length_B': '389'},
# 'key2': {'length_A': '865', 'length_B': '553'}})