[英]Convert a list with duplicating keys into a dictionary and sum the values for each duplicating key
[英]Duplicating dictionary with random values
我有一個示例字典,我想用隨機值復制它以創建測試數據。 我正在使用隨機函數來生成值,但它沒有按預期工作。 因為我想在側字典中填充列表以及創建不同的鍵。 下面是我的示例字典。
a = {
"6335050000000172": [
{
"accBalance": 6,
"accNum": 6335050000000172,
"activityCode": 440,
"activityDate": "2021-09-27 00:00:00",
"creditsDebits": 0,
"displayPostage": "",
"meterSerialNumber": 0,
"postage": 0,
"timeZone": "",
"transactionDescription": "PAYMENT THANK YOU"
}
]
}
我的重復代碼:
times = ["2021-09-27 00:00:00", "2021-08-27 00:00:00","2021-07-27 00:00:00","2021-06-27 00:00:00","2021-05-27 00:00:00","2021-03-27 00:00:00"]
c = ["6335050000000172","6335052000143333","6335051000136685","6335052030050953","6335050000000313","6335052030050185"]
transactionDescription = ['DIRECT DEBIT PAYMENT THANK YOU', 'METER REFILL', 'METER RESET', 'PAYMENT RECEIVED' ]
b = {}
i = 0
while i <= 3:
#for i in range(100):
for j in a.values():
j[0]['accBalance'] = random.randint(0,100)
j[0]['transactionDescription'] = random.choice(transactionDescription)
j[0]['accNum'] = random.choice(c)
j[0]['activityDate'] = random.choice(times)
if j[0]['accNum'] in b.keys():
j.append(j[0]['accNum'])
else:
b[j[0]['accNum']] = j
#print(b)
i = i + 1
print(b)
#f = open("output.txt", "a")
#print(b, file=f)
#f.close()
我正在嘗試獲得如下示例輸出:
{'6335050000000172': [{...},{...},...m], '6335052000143333': [{..}...m] ......., n }
也許像這樣?
import random
from collections import defaultdict
def get_data(n):
res = defaultdict(list)
c = ["6335050000000172",
"6335052000143333",
"6335051000136685",
"6335052030050953",
"6335050000000313",
"6335052030050185"]
times = [
"2021-09-27 00:00:00",
"2021-08-27 00:00:00",
"2021-07-27 00:00:00",
"2021-06-27 00:00:00",
"2021-05-27 00:00:00",
"2021-03-27 00:00:00"
]
transactionDescription = ['DIRECT DEBIT PAYMENT THANK YOU', 'METER REFILL', 'METER RESET', 'PAYMENT RECEIVED']
for i in range(n):
title = random.choice(c)
res[title].append(
{
"accBalance": random.randint(0,100),
"accNum": title,
"activityCode": 440,
"activityDate": random.choice(times),
"creditsDebits": 0,
"displayPostage": "",
"meterSerialNumber": 0,
"postage": 0,
"timeZone": "",
"transactionDescription": random.choice(transactionDescription)
}
)
return res
print(get_data(10))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.