Python字典无法正确填充for循环

时间:2017-11-01 09:31:12

标签: python json dictionary

我目前正在为基于浏览器的javascript数据库制作一些测试数据。我从网站上删除了一些数据并用它填充了一个python列表。现在我正在尝试填充字典,添加一些其他随机数据并制作一个json文件。我的变数:

  • cpartyList:元组列表。每个元组由4个字符串组成:Number1(唯一),Number2,fullname,address;
  • cpartyDict:一个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()中有两个键)。有什么问题?

1 个答案:

答案 0 :(得分:-1)

您的代码正在运作..

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': ''}}