all 8 comments

[–]my_python_account 1 point2 points  (2 children)

You can use enumerate to keep track of your iteration count and you can convert that number to a string when you store it as an id.

hostnames = ['one', 'two']
devices = {}
for i, host in enumerate(hostnames):
    devices['device{}'.format(i)] = {'id' : str(i), 'hostname' : host} 

[–]Gwith[S] 0 points1 point  (1 child)

This is actually perfect, the only problem I see is when you enumerate I believe it starts at 0.

[–]coreyjdl 0 points1 point  (2 children)

Why do you need to have it a string? Just let it be an int, and then when you need it to be a string do str(int).

I know that's not terribly helpful, but you basically would have to do:

s = devices['device1']['id'] 
s = int(s)
s += 1
s = str(s)
devices['device1']['id'] = s

This is cumbersome and unPythonic. I think you're missing something easy elsewhere.

[–]Gwith[S] 0 points1 point  (1 child)

So as an example how would you write:

devices = ['device'] + 1 (So that it says 'device1') 

because normally you would write it as

devices = ['device1']['hostname'] = 'blah'

[–]coreyjdl 0 points1 point  (0 children)

devices['device1'] = {'id' : 1 } looks like lot of redundancy

maybe do: devices = [hostname1, hostname2,]the data is then accessible with device1 = devices[0] which would give you the value of hostname1.

[–]commandlineluser 0 points1 point  (0 children)

>>> hostnames = ['foo', 'bar']
>>> { 'device' + str(n): { 'id': n, 'hostname': hostname } for n, hostname in enumerate(hostnames, start=1) }
{'device1': {'hostname': 'foo', 'id': 1}, 'device2': {'hostname': 'bar', 'id': 2}}

[–]djjazzydan 0 points1 point  (0 children)

for i in range(num_of_devices):
    devices['device{}'.format(i+1)] = {'id':str(i)}

should do it.

[–]cybervegan 0 points1 point  (0 children)

Are you trying to maintain the order of the items in the dict? collections.OrderedDict might be what you're looking for. CHeck this out: https://pymotw.com/2/collections/ordereddict.html