PYTHONL Telegram 5101
This media is not supported in your browser
VIEW IN TELEGRAM
🖥 Python trick: группировка с помощью itertools.groupby

Иногда при работе с коллекциями в пайтон нужно быстро сгруппировать данные по ключу и при этом не писать громоздкий цикл с проверками. В таких случаях можно использовать модуль итэртулз и функцию группбай. Она позволяет превратить список в словарь с удобной структурой, где каждый ключ сразу содержит все связанные элементы. Это сильно экономит строки кода и делает его чище.



from itertools import groupby
from operator import itemgetter

data = [
{"category": "A", "value": 10},
{"category": "B", "value": 20},
{"category": "A", "value": 30},
{"category": "B", "value": 40},
]

сортировка обязательна перед groupby
data.sort(key=itemgetter("category"))

grouped = {
key: list(group) for key, group in groupby(data, key=itemgetter("category"))
}

print(grouped)
Please open Telegram to view this post
VIEW IN TELEGRAM
16👍9🔥3



tgoop.com/pythonl/5101
Create:
Last Update:

🖥 Python trick: группировка с помощью itertools.groupby

Иногда при работе с коллекциями в пайтон нужно быстро сгруппировать данные по ключу и при этом не писать громоздкий цикл с проверками. В таких случаях можно использовать модуль итэртулз и функцию группбай. Она позволяет превратить список в словарь с удобной структурой, где каждый ключ сразу содержит все связанные элементы. Это сильно экономит строки кода и делает его чище.



from itertools import groupby
from operator import itemgetter

data = [
{"category": "A", "value": 10},
{"category": "B", "value": 20},
{"category": "A", "value": 30},
{"category": "B", "value": 40},
]

сортировка обязательна перед groupby
data.sort(key=itemgetter("category"))

grouped = {
key: list(group) for key, group in groupby(data, key=itemgetter("category"))
}

print(grouped)

BY Python/ django


Share with your friend now:
tgoop.com/pythonl/5101

View MORE
Open in Telegram


Telegram News

Date: |

Telegram desktop app: In the upper left corner, click the Menu icon (the one with three lines). Select “New Channel” from the drop-down menu. During a meeting with the president of the Supreme Electoral Court (TSE) on June 6, Telegram's Vice President Ilya Perekopsky announced the initiatives. According to the executive, Brazil is the first country in the world where Telegram is introducing the features, which could be expanded to other countries facing threats to democracy through the dissemination of false content. Invite up to 200 users from your contacts to join your channel How to Create a Private or Public Channel on Telegram? With Bitcoin down 30% in the past week, some crypto traders have taken to Telegram to “voice” their feelings.
from us


Telegram Python/ django
FROM American