[英]Python dictionary not filling properly in for loop
I am currently making some test data for my browser-based javascript database.我目前正在为我的基于浏览器的 javascript 数据库制作一些测试数据。 I scraped some data off of a web-site and filled a python list with it.
我从一个网站上抓取了一些数据,并用它填充了一个 python 列表。 Now i am trying to populate a dictionary, add some other random data and make a json file.
现在我正在尝试填充字典,添加一些其他随机数据并制作一个 json 文件。 My variables:
我的变量:
cpartyList consists of 40 tuples. cpartyList 由 40 个元组组成。 Now, populating my dictionary with data:
现在,用数据填充我的字典:
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())
But in return i only get 2 last tuples in my dictionary (cpartyDict.keys() has two keys in it).但作为回报,我只得到字典中的最后 2 个元组(cpartyDict.keys() 中有两个键)。 What is wrong?
怎么了?
YOUR CODE IS WORKING..您的代码正在运行...
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)
RESULT结果
{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.