Max Weaver Max Weaver - 11 months ago 51
Python Question

Change a dictionary value whilst iterating over it

So I have the following code which iterates over a list and uses the data to populate a dict. = [["", "123", "A", ""],["", "122", "NS", ""]]

for each_list in
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', '')]

I realise this probably isn't very Pythonic, so any suggestions on how to do this more eloquently would be appreciated

Anyhoo, what I want to do is add a random value to each key generated as the code loops through the data.

So where it says
self.terrarecord[each_list[0].replace('.', '')] = {
I want to add a randomly generated number on the end, so the finished result might look something like this:

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


As you can see in the loop it is using the same data in the
list to populate more than one key, and the first one needs to be unique hence why I want to add the integer as I loop through.

I hope this makes sense. It's quite difficult to explain.


Answer Source

How about something like this:

import random

rand_key = random.randint(1, 100)

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

You can adjust the range you want the random number to be chosen from with the arguments to randint(). Not that this will make it difficult to access the values from this dict however.

Also, there is a potential with this method for having data overwritten if each_list[0].replace('.', '') and rand_key happen to have the same value as a previous key. If this is not an issue, then this method should work for you. If it is, you could generate your "random" number with a timestamp:

from datetime import datetime

rand_key ='%Y%m%d%s%f')

Which should give you a unique key unless the same value for each_list[0].replace('.', '') comes up twice in the same microsecond. See for an explanation of the format codes passed to strftime().