How do I split list of dict in Python? - python

lis_dict = [
{item: "some item"},
{quantity: 2},
{id: 10},
{quantity: 2},
{id: 11},
{quantity: 2},
{quantity: 2},
{id: 12}
]
I have above list of dict, which I would like to split into a sub-list.
result = [
[{item: "some item"}, {quantity: 2}, {id: 10}],
[{quantity: 2}, {id: 11}],
[{quantity: 2}, {quantity: 2}, {id: 12}]
]

The question asks to split the list by "id" into a nested list.
Input:
lis_dict
[{'item': 'some item'},
{'quantity': 2},
{'id': 10},
{'quantity': 2},
{'id': 11},
{'quantity': 2},
{'quantity': 2},
{'id': 12}]
Code:
result = []
s = 0
for i,j in enumerate(lis_dict):
if ("id" in j.keys()):
result.append(lis_dict[s:i+1])
s = i+1
Prints:
[[{'item': 'some item'}, {'quantity': 2}, {'id': 10}],
[{'quantity': 2}, {'id': 11}],
[{'quantity': 2}, {'quantity': 2}, {'id': 12}]]

A more general approach might be the following (in which you could add more dictionaries in a sublist):
lis_dict = [{'item': 'some item'},
{'quantity': 2},
{'id': 10},
{'quantity': 2},
{'item': 'some item'},
{'id': 11},
{'quantity': 2},
{'quantity': 2},
{'id': 12}]
result = []
sublist = []
for d in lis_dict:
sublist.append(d)
if d.get("id"):
result.append(sublist)
sublist = []
print(result)
# [[{'item': 'some item'}, {'quantity': 2}, {'id': 10}], [{'quantity': 2},
# {'item': 'some item'}, {'id': 11}], [{'quantity': 2}, {'quantity': 2}, {'id': 12}]]

Related

Python: Descending order and just 3 objects has a high value [duplicate]

This question already has answers here:
How do I sort a list of dictionaries by a value of the dictionary?
(20 answers)
Closed 6 months ago.
I have an array object like that, Not sort value, I want descending order and just 3 objects has a high value:
[{'id': 1, 'value': 3},
{'id': 2, 'value': 6},
{'id': 3, 'value': 8},
{'id': 4, 'value': 8},
{'id': 5, 'value': 10},
{'id': 6, 'value': 9},
{'id': 7, 'value': 8},
{'id': 8, 'value': 4},
{'id': 9, 'value': 5}]
I want result is descending order and just 3 objects have a high value, like this
[{'id': 5, 'value': 10},
{'id': 6, 'value': 9},
{'id': 7, 'value': 8},
{'id': 3, 'value': 8},
{'id': 4, 'value': 8},]
Please help me, thanks
t = [{'id': 1, 'value': 3},
{'id': 2, 'value': 6},
{'id': 3, 'value': 8},
{'id': 4, 'value': 8},
{'id': 5, 'value': 10},
{'id': 6, 'value': 9},
{'id': 7, 'value': 8}]
newlist = sorted(t, key=lambda d: d['value'])
newlist.reverse()
print(newlist[:3])
# [{'id': 5, 'value': 10}, {'id': 6, 'value': 9}, {'id': 7, 'value': 8}]
More info about list slicing
More info about reverse()
More info

Split a list of dictionaries into multiple chunks

I have this one list
list_dict = [
{'id': 1},
{'item': 'apple'},
{'id': 2},
{'item': 'pear'},
{'id': 1},
{'item': 'peach'},
{'id': 2},
{'item': 'kiwi'},
{'id': 3},
{'item': 'banana'},
{'id': 4},
{'item': 'mango'},
{'id': 1},
{'item': 'watermelon'},
{'id': 2},
{'item': 'plum'},
{'id': 3},
{'item': 'grapes'}]
and I want to split like this (start to make sublist when "id" is 1)
result = [
[{'id': 1},
{'item': 'apple'},
{'id': 2},
{'item': 'pear'}],
[{'id': 1},
{'item': 'peach'},
{'id': 2},
{'item': 'kiwi'},
{'id': 3},
{'item': 'banana'},
{'id': 4},
{'item': 'mango'}],
[{'id': 1},
{'item': 'watermelon'},
{'id': 2},
{'item': 'plum'},
{'id': 3},
{'item': 'grapes'}]]
Some nested for loop will work
list_dict = [{"id":1},{"item":"apple"},{"id":2},{"item":"pear"},{"id":1},{"item":"peach"},{"id":2},{"item":"kiwi"},{"id":3},{"item":"banana"},{"id":4},{"item":"mango"},{"id":1},{"item":"watermelon"},{"id":2},{"item":"plum"},{"id":3},{"item":"grapes"}]
output = []
temp = []
for i in list_dict:
if i.get('id', -1) == 1 and temp:
output.append(temp.copy())
temp.clear()
temp.append(i)
else:
temp.append(i)
output.append(temp.copy())
print(output)
#[[{'id': 1}, {'item': 'apple'}, {'id': 2}, {'item': 'pear'}], [{'id': 1}, {'item': 'peach'}, {'id': 2}, {'item': 'kiwi'}, {'id': 3}, {'item': 'banana'}, {'id': 4}, {'item': 'mango'}], [{'id': 1}, {'item': 'watermelon'}, {'id': 2}, {'item': 'plum'}, {'id': 3}, {'item': 'grapes'}]]
Maybe something like this?
main_list = []
current_list = []
for el in list_dict:
if el.get("id", 0) == 1:
if current_list:
main_list.append(current_list)
current_list = [el]
else:
current_list.append(el)
if current_list:
main_list.append(current_list)
print(main_list)

How to convert key to value in dictionary type?

I have a question about the convert key.
First, I have this type of word count in Data Frame.
[Example]
dict = {'forest': 10, 'station': 3, 'office': 7, 'park': 2}
I want to get this result.
[Result]
result = {'name': 'forest', 'value': 10,
'name': 'station', 'value': 3,
'name': 'office', 'value': 7,
'name': 'park', 'value': 2}
Please check this issue.
As Rakesh said:
dict cannot have duplicate keys
The closest way to achieve what you want is to build something like that
my_dict = {'forest': 10, 'station': 3, 'office': 7, 'park': 2}
result = list(map(lambda x: {'name': x[0], 'value': x[1]}, my_dict.items()))
You will get
result = [
{'name': 'forest', 'value': 10},
{'name': 'station', 'value': 3},
{'name': 'office', 'value': 7},
{'name': 'park', 'value': 2},
]
As Rakesh said, You can't have duplicate values in the dictionary
You can simply try this.
dict = {'forest': 10, 'station': 3, 'office': 7, 'park': 2}
result = {}
count = 0;
for key in dict:
result[count] = {'name':key, 'value': dict[key]}
count = count + 1;
print(result)

how to make values of a key of a dic uniqe?

I have a list of dic. the value contains some results. I want to uniq them. (some of them are repetitive)
Example of dic[0]:
{'key': 'art director',
'Results': [{'actor': 1},
{'art director': 4},
{'creative designer': 2},
{'art director': 4},
{'creative designer': 2},
{'digital designer': 1},
{'graphic designer': 1},
{'communications consultant': 1},
{'designer': 1},
{'art director': 4},
{'art director': 4}]}
output:
{'key': 'art director',
'Results': [{'actor': 1},
{'art director': 4},
{'creative designer': 2},
{'digital designer': 1},
{'graphic designer': 1},
{'communications consultant': 1},
{'designer': 1},
]}
I wanted to use loop and use the following if condition:
if dic[i]['Results'][k]==dic[i]['Results'][j]
but it is not efficient at all. since there are 3 indices. any better way?
You could use a dictionary for your "Results" values rather than a list of single key dictionaries. So the following:
{
'key': 'art director',
'Results': [
{'actor': 1},
{'art director': 4},
{'creative designer': 2},
{'art director': 4},
{'creative designer': 2},
{'digital designer': 1},
{'graphic designer': 1},
{'communications consultant': 1},
{'designer': 1},
{'art director': 4},
{'art director': 4}
]
}
becomes
import pprint
pprint.pprint({
'key': 'art director',
'Results': {
'actor': 1,
'art director': 4,
'creative designer': 2,
'art director': 4,
'creative designer': 2,
'digital designer': 1,
'graphic designer': 1,
'communications consultant': 1,
'designer': 1,
'art director': 4,
'art director': 4
}
})
Since dictionaries can only have one value per key, this will automatically handle deduplication as you build the Results dictionary.
You can use this line, in order to take the whole list (The value of the key 'Result') and check for duplicates, then change it accordingly if it is already inside your key.
d['Results'] = [dict(t) for t in {tuple(d.items()) for d in d['Results']}]
I have two solutions.
Solution 1
This first one will output exactly what you pretended:
res = [] # represents the final results list
aux = {} # used to check if the key is already in 'Results': []
for i in dic:
for r in i['Results']:
for k,v in r.items():
if k not in aux.keys():
aux[k] = v
res.append({k:v})
i['Results'] = res
print(dic)
Solution 2
This second one will transform 'Results' value in dic[I] into a single dictionary instead of a list of dictionaries:
res = {}
for i in dic:
for r in i['Results']:
for k,v in r.items():
res[k] = v
i['Results'] = res
print(dic)
Using your input as an example:
Output:
[{'Results': {'actor': 1,
'art director': 4,
'communications consultant': 1,
'creative designer': 2,
'designer': 1,
'digital designer': 1,
'graphic designer': 1},
'key': 'art director'}]
Sample dic:
dic = [{'key': 'art director',
'Results': [{'actor': 1},
{'art director': 4},
{'creative designer': 2},
{'art director': 4},
{'creative designer': 2},
{'digital designer': 1},
{'graphic designer': 1},
{'communications consultant': 1},
{'designer': 1},
{'art director': 4},
{'art director': 4}]}]

Separate list elements by theirs property in Python

I have list p1:
p1 = [
{'id': 1, 'area': 5},
{'id': 2, 'area': 6},
{'id': 3, 'area': 10},
{'id': 4, 'area': 6},
{'id': 5, 'area': 6},
{'id': 6, 'area': 6},
{'id': 7, 'area': 4},
{'id': 8, 'area': 4}
]
And I need to separate this list by area value, like this (p2):
p2 = {
4: [
{'id': 7, 'area': 4},
{'id': 8, 'area': 4}
],
5: [
{'id': 1, 'area': 5}
],
6: [
{'id': 2, 'area': 6},
{'id': 4, 'area': 6},
{'id': 5, 'area': 6},
{'id': 6, 'area': 6}
],
10: [
{'id': 3, 'area': 10}
]
}
My solution is:
areas = {x['area'] for x in p1}
p2 = {}
for area in areas:
p2[area] = [x for x in p1 if x['area'] == area]
It seems to work, but is there any better and more "pythonic" solution?
Using groupby you get
>>> import itertools
>>> f = lambda t: t['area']
>>> {i: list(b) for i, b in itertools.groupby(sorted(p1, key=f), key=f)}
Gives
{4: [{'area': 4, 'id': 7},
{'area': 4, 'id': 8}],
5: [{'area': 5, 'id': 1}],
6: [{'area': 6, 'id': 2},
{'area': 6, 'id': 4},
{'area': 6, 'id': 5},
{'area': 6, 'id': 6}],
10: [{'area': 10, 'id': 3}]}
edit: If you don't like using lambdas you can also do, as suggested by bro-grammer
>>> import operator
>>> f = operator.itemgetter('area')
You can simply use defaultdict:
from collections import defaultdict
result = defaultdict(list)
for i in p1:
result[i['area']].append(i)
Yes, use one of the grouping idioms. Using a vanilla dict:
In [15]: p1 = [
...: {'id': 1, 'area': 5},
...: {'id': 2, 'area': 6},
...: {'id': 3, 'area': 10},
...: {'id': 4, 'area': 6},
...: {'id': 5, 'area': 6},
...: {'id': 6, 'area': 6},
...: {'id': 7, 'area': 4},
...: {'id': 8, 'area': 4}
...: ]
In [16]: p2 = {}
In [17]: for d in p1:
...: p2.setdefault(d['area'], []).append(d)
...:
In [18]: p2
Out[18]:
{4: [{'area': 4, 'id': 7}, {'area': 4, 'id': 8}],
5: [{'area': 5, 'id': 1}],
6: [{'area': 6, 'id': 2},
{'area': 6, 'id': 4},
{'area': 6, 'id': 5},
{'area': 6, 'id': 6}],
10: [{'area': 10, 'id': 3}]}
Or more neatly, using a defaultdict:
In [23]: from collections import defaultdict
In [24]: p2 = defaultdict(list)
In [25]: for d in p1:
...: p2[d['area']].append(d)
...:
In [26]: p2
Out[26]:
defaultdict(list,
{4: [{'area': 4, 'id': 7}, {'area': 4, 'id': 8}],
5: [{'area': 5, 'id': 1}],
6: [{'area': 6, 'id': 2},
{'area': 6, 'id': 4},
{'area': 6, 'id': 5},
{'area': 6, 'id': 6}],
10: [{'area': 10, 'id': 3}]})

Categories