-1

maybe this question is asked before but I have a list of dictionaries that I need to split it into smaller chunks with returning the only specific values of that dictionaries.

my_list = [
    {"name": "q", "id":1},
    {"name": "w", "id":2},
    {"name": "z", "id":3},
    {"name": "f", "id":44},
    {"name": "k", "id":55},
    {"name": "d", "id":8},
    {"name": "t", "id":25},
]

n = 4

x = [my_list[i:i + n] for i in range(0, len(my_list), n)]
print(x)

this code works perfectly fine but I need to return only ids:

[[1, 2, 33, 44], [55, 8, 25]]
Babak Abadkheir
  • 2,222
  • 1
  • 19
  • 46
  • can you elaborate what you need the code to do? if the code works what is the problem? – Dr. Prof. Patrick Aug 23 '20 at 07:47
  • @skinny_func I said in last line , I need to return only ids into my splitted arrays – Babak Abadkheir Aug 23 '20 at 07:50
  • Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks). You can use that with the list of ids: `ids = [d['id'] for d in my_list]` – Tomerikoo Aug 23 '20 at 07:52
  • there is no `33` in your provided input, did you mean `3`? – DirtyBit Aug 23 '20 at 07:54

3 Answers3

3

Get all the ids from the list of dict and then create sub-lists of n sized lists from it:

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]
 
my_list = [
    {'name': "q", 'id':1},
    {'name': "w", 'id':2},
    {'name': "z", 'id':3},
    {'name': "f", 'id':44},
    {'name': "k", 'id':55},
    {'name': "d", 'id':8},
    {'name': "t", 'id':25},
]

ids = [dd['id'] for dd in my_list]   # [1,2,3,44,55,8,25]
print(list(chunks(ids, 4)))

OUTPUT:

[[1, 2, 3, 44], [55, 8, 25]]   
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
2

This will work. Let me know any questions.

my_list = [
    {"name": "q", "id":1},
    {"name": "w", "id":2},
    {"name": "z", "id":3},
    {"name": "f", "id":44},
    {"name": "k", "id":55},
    {"name": "d", "id":8},
    {"name": "t", "id":25},
]

n = 4

x = [[y["id"] for y in my_list[i:i + n]] for i in range(0, len(my_list), n)]
print(x)
JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24
1

my_list[i: i + n] will create a sliced list out of the original list on which you have to iterate to get the id present in the dictionary.

x = [
    [j["id"] for j in my_list[i: i + n]] for i in range(0, len(my_list), n)
]
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33