[英]Python dictionary not filling properly in for loop
我目前正在為我的基於瀏覽器的 javascript 數據庫制作一些測試數據。 我從一個網站上抓取了一些數據,並用它填充了一個 python 列表。 現在我正在嘗試填充字典,添加一些其他隨機數據並制作一個 json 文件。 我的變量:
cpartyList 由 40 個元組組成。 現在,用數據填充我的字典:
for org in cpartyList:
#just to make shure that a tuple is 4 units and Number1 is unique
if len(org) == 4 and org[0] not in cpartyDict.keys():
cpartyDict[org[0]] = {
"Number1": org[0],
"Number2": org[1],
"shortname": "",
"fullname": org[2],
"contacts": {
"adressOfficial": org[3],
"adressPostal": org[3],
"phone": ''.join([str(random.randint(0,9)) for i in range(11)])
}
}
print(cpartyDict,keys())
但作為回報,我只得到字典中的最后 2 個元組(cpartyDict.keys() 中有兩個鍵)。 怎么了?
您的代碼正在運行...
import random
import pprint
cpartyList= [
(1,'c1','c2','c3'),
(2,'c1','c2','c3','c4'),
(3,'c1','c2','c3'),
(4,'c1','c2','c3','c4','c5'),
(5,'c1','c2','c3'),
(6,'c1','c2','c3')
]
cpartyDict = {}
for org in cpartyList:
#just to make shure that a tuple is 4 units and Number1 is unique
if len(org) == 4 and org[0] not in cpartyDict.keys():
cpartyDict[org[0]] = {
"Number1": org[0],
"Number2": org[1],
"shortname": "",
"fullname": org[2],
"contacts": {
"adressOfficial": org[3],
"adressPostal": org[3],
"phone": ''.join([str(random.randint(0,9)) for i in range(11)])
}
}
pprint.pprint(cpartyDict)
結果
{1: {'Number1': 1,
'Number2': 'c1',
'contacts': {'adressOfficial': 'c3',
'adressPostal': 'c3',
'phone': '78858320412'},
'fullname': 'c2',
'shortname': ''},
3: {'Number1': 3,
'Number2': 'c1',
'contacts': {'adressOfficial': 'c3',
'adressPostal': 'c3',
'phone': '40650498587'},
'fullname': 'c2',
'shortname': ''},
5: {'Number1': 5,
'Number2': 'c1',
'contacts': {'adressOfficial': 'c3',
'adressPostal': 'c3',
'phone': '17115487396'},
'fullname': 'c2',
'shortname': ''},
6: {'Number1': 6,
'Number2': 'c1',
'contacts': {'adressOfficial': 'c3',
'adressPostal': 'c3',
'phone': '54560186092'},
'fullname': 'c2',
'shortname': ''}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.