3/14/2023

split dict item as ratio

 sperate dict item as ratio.

refer to code:



.

import random

def split_dict(d, train_ratio=0.9):
# Convert the dictionary to a list of tuples and shuffle it
items = list(d.items())
random.shuffle(items)

# Calculate the indexes for the split
split_idx = int(train_ratio * len(items))

# Split the list into two lists containing train_ratio and (1 - train_ratio) of the items
train_items = items[:split_idx]
test_items = items[split_idx:]

# Convert the two lists back to dictionaries
train_dict = {k: v for k, v in train_items}
test_dict = {k: v for k, v in test_items}

return train_dict, test_dict




my_dict = {'apple': 2, 'banana': 3, 'orange': 1, 'kiwi': 4, 'pineapple': 5}
train_dict, test_dict = split_dict(my_dict, train_ratio=0.9)
print(train_dict)
print(test_dict)


..


Thank you.


No comments:

Post a Comment