user3809411
user3809411

Reputation: 346

Break list of dictionaries depending upon the keys of dictionary without lossing order

Consider a list

temp=[
{'white': ['BlackRock Institutional Trust Company, N.A.  400 Howard Street  San Francisco, CA 94105-2618', ' ', '1,741,814', '', ' ', ' ', ' 6.85%', ' ']},
{'white': ['The Banc Funds Co, LLC  20 North Wacker Drive    Suite 3300  Chicago, IL 60606-3105', ' ', '1,447,529', '', ' ', ' ', ' 5.69%', ' ']}, 
{'blue': ['James B. Miller, Jr.', ' ', '3,413,249', '', '(1)     ', ' ', '13.40%', ' ']}, 
{'blue': ['Major General (Ret) David R. Bockel', ' ', '41,471', '', '(2)    ', ' ', ' *', ' ']}, 
{'white': ['Wm. Millard Choate', ' ', '221,581', '', '(3)   ', ' ', ' *', ' ']}, 
{'white': ['Dr. Donald A. Harp, Jr.', ' ', '40,892', '', '(4)   ', ' ', ' *', ' ']}, 
{'white': ['Kevin S. King', ' ', '53,124', '', '(5)  ', ' ', ' *', ' ']}, 
{'white': ['William C. Lankford, Jr.', ' ', '32,043', '', '(6)  ', ' ', ' *', ' ']}, 
{'white': ['H. Palmer Proctor, Jr.', ' ', '309,384', '', '(7)  ', ' ', '1.22%', ' ']}, 
{'white': ['W. Clyde Shepherd III', ' ', '349,450', '', '(8)     ', ' ', '1.37%', ' ']}, 
{'white': ['Rankin M. Smith, Jr.', ' ', '303,768', '', '(9)  ', ' ', '1.19%', ' ']}, 
{'white': ['Stephen H. Brolly', ' ', '48,958', '', ' ', ' ', ' *', ' ']}, 
{'blue': ['David Buchanan', ' ', '278,601', '', ' ', ' ', '1.10%', ' ']}, 
{'blue': ['All directors and executive officers  as a group (11 persons)', ' ', '5,092,521', '', '(10)  ', ' ', '19.93%', ' ']}
]

I want to break the list into different list whenever the key of dictionary changes. The desired output would be

[{'white': ['BlackRock Institutional Trust Company, N.A.  400 Howard Street  San Francisco, CA 94105-2618', ' ', '1,741,814', '', ' ', ' ', ' 6.85%', ' ']}, {'white': ['The Banc Funds Co, LLC  20 North Wacker Drive   Suite 3300  Chicago, IL 60606-3105', ' ', '1,447,529', '', ' ', ' ', ' 5.69%', ' ']}]
[{'blue': ['James B. Miller, Jr.', ' ', '3,413,249', '', '(1)    ', ' ', '13.40%', ' ']}, {'blue': ['Major General (Ret) David R. Bockel', ' ', '41,471', '', '(2)  ', ' ', ' *', ' ']}]
[{'white': ['Wm. Millard Choate', ' ', '221,581', '', '(3)  ', ' ', ' *', ' ']}, {'white': ['Dr. Donald A. Harp, Jr.', ' ', '40,892', '', '(4)  ', ' ', ' *', ' ']}, {'white': ['Kevin S. King', ' ', '53,124', '', '(5)  ', ' ', ' *', ' ']}, {'white': ['William C. Lankford, Jr.', ' ', '32,043', '', '(6)  ', ' ', ' *', ' ']}, {'white': ['H. Palmer Proctor, Jr.', ' ', '309,384', '', '(7)  ', ' ', '1.22%', ' ']}, {'white': ['W. Clyde Shepherd III', ' ', '349,450', '', '(8)  ', ' ', '1.37%', ' ']}, {'white': ['Rankin M. Smith, Jr.', ' ', '303,768', '', '(9)  ', ' ', '1.19%', ' ']}, {'white': ['Stephen H. Brolly', ' ', '48,958', '', ' ', ' ', ' *', ' ']}]
[{'blue': ['David Buchanan', ' ', '278,601', '', ' ', ' ', '1.10%', ' ']}, {'blue': ['All directors and executive officers  as a group (11 persons)', ' ', '5,092,521', '', '(10)  ', ' ', '19.93%', ' ']}]

Key can be more than two (i.e., white and blue)

For now i came up with this logic, but is there any simple or short way to do this.

def format(temp):
    i=0
    tmp_list = []
    while i<len(temp):
        found=False
        for color1 in  temp[i]:
            if i+1<len(temp):
                for color2 in temp[i+1]:
                    if color1!=color2:
                        tmp_list.append(temp[i])
                        tmp_list.append("changed")
                        found=True
        if found==False:
            tmp_list.append(temp[i])
        i=i+1
    final_list = []
    another_lis = []
    for tl in tmp_list:
        if tl!='changed':
            another_lis.append(tl)
        else:
            final_list.append(another_lis)
            another_lis = []

    return final_list

whole_list = format(temp)

for wl in whole_list:
    print(wl)

Upvotes: 2

Views: 83

Answers (2)

Chris
Chris

Reputation: 22953

An nice way to do this is to use itertools.groupby:

from itertools import groupby
temp = [...]
data = [list(g) for _, g in groupby(temp, key=dict.keys)]

However, as pointed out by Eli Korvigo, this solution is only works with multi-key dictionaries in Python 3.x, since on Python 2.x, dict.keys() returns a list object, which is order-sensitive when being compared. As Eli states, an appropriate substitute to use in Python 2.x would be a data structure such as a set.

Upvotes: 5

iGian
iGian

Reputation: 11193

I like to have a custom method like the one here below, to be used whenever a slicing on condition between consecutive elements is required.

def chunk_while(predicate, iterable):
  i, x, size = 0, 0, len(iterable)
  while i < size-1:
    if not predicate(iterable[i], iterable[i+1]):
      yield iterable[x:i+1]
      x = i + 1
    i += 1
  yield iterable[x:size]

In this case it can be used in this way:

slices = chunk_while(lambda x,y: list(x) == list(y), temp)

The result is generator for a a nested array:

print(list(slices))

# [
#   [{'white': ['BlackRock Institutional ...', '..']}, {'white': ['The Banc Funds ...', '..']}],
#   [{'blue': ['James B. Miller, Jr.', '..']}, {'blue': ['Major General (Ret) ...']}],
#   [{'white': ['Wm. Millard Choate', '..']}, {'white': ['Dr. Donald A. Harp, Jr.', '..']}, {'white': ['Kevin S. King', '..']}, {'white': ['William C. Lankford, Jr.', '..']}, {'white': ['H. Palmer Proctor, Jr.', '..']}, {'white': ['W. Clyde Shepherd III', '..']}, {'white': ['Rankin M. Smith, Jr.', '..']}, {'white': ['Stephen H. Brolly', '..']}],
#   [{'blue': ['David Buchanan', '..']}, {'blue': ['All directors and executive ...', '..']}]
# ]

Upvotes: 1

Related Questions