在迭代时更改字典值

时间:2016-11-18 15:39:06

标签: python loops dictionary

所以我有以下代码迭代列表并使用数据来填充字典。

self.data = [["name1.co.uk", "123", "A", "1.2.3.4"],["name2.com", "122", "NS", "ns1.google.com"]]

for each_list in self.data:
            self.terrarecord[each_list[0].replace('.', '')] = {
                "zone_id": self.zone_id,
                "name": each_list[0] + self.url, # not sure if I need to do this
                "type": each_list[2],
                "ttl": each_list[1],
                "records": [each_list[3].replace('\n', '')]
            }

我意识到这可能不是非常Pythonic,所以任何有关如何更加雄辩地做这件事的建议都会受到赞赏

Anyhoo,我想要做的是为代码循环遍历数据时生成的每个密钥添加一个随机值。

所以它说self.terrarecord[each_list[0].replace('.', '')] = {我希望在最后添加一个随机生成的数字,所以完成的结果可能如下所示:

"key123" { # <-- This is the key that needs a random number
    "id": "id",
    "name": "key.co.uk",
    "type": "SOA",
    "records": ["1234 etc"]

}

正如您在循环中看到的那样,它使用data列表中的相同数据来填充多个键,并且第一个键需要是唯一的,因此我想在I循环中添加整数通过

我希望这是有道理的。这很难解释。

由于

2 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

import random

...
rand_key = random.randint(1, 100)

self.terrarecord[each_list[0].replace('.', '') + str(rand_key)] = {
...
}

您可以使用randint()的参数调整您希望从中选择随机数的范围。但这并不是很难从dict访问这些值。

此外,如果each_list[0].replace('.', '')rand_key碰巧与前一个键具有相同的值,则此方法可能会覆盖数据。如果这不是问题,那么此方法应该适合您。如果是,您可以生成&#34;随机&#34;带时间戳的数字:

from datetime import datetime

rand_key = datetime.now().strftime('%Y%m%d%s%f')

除非each_list[0].replace('.', '')的相同值在相同的微秒内出现两次,否则应该为您提供唯一的密钥。有关传递给strftime()的格式代码的说明,请参见http://strftime.org/

答案 1 :(得分:0)

因此,您可能希望使用randint来获取随机值,但您还需要确保在each_list[0]可以相同之前不使用随机数(如果它们不是' t idk为什么你需要附加一个随机值)。

from random import randint

data = [["name1.co.uk", "123", "A", "1.2.3.4"],["name2.com", "122", "NS", "ns1.google.com"]]
terrarecord={}

def getRandKey(name,record,key_length=3):
  min=int('1'+'0'*(key_length-1))
  max=int('9'*key_length)
  r=randint(min,max)
  new_name=name+str(r)
  while new_name in record:
    r=randint(min,max)
    new_name=name+str(r)
  return new_name

for each_list in data:
    terrarecord[getRandKey(each_list[0].replace('.', ''),terrarecord)] = {
                "zone_id": 5,
                "name": each_list[0], 
                "type": each_list[2],
                "ttl": each_list[1],
                "records": [each_list[3].replace('\n', '')]
    }