Cancel
Showing results for
Did you mean:

# NX11 Python Indexing Dictionary and Setting Random Numbers

Creator

Hello, I would like some help with the following.  Sorry if the code semantics is not entirely correct (using a lot of pseudo code in this post)  but I hope to show what I am referring to with enough detail so I can get some help.

I am writing a script which cycles thru sheet bodies in the workpart. Each sheet has an attribute associated with it and so I am storing each attribute in the following dictionary:

listA = {}

listB = {}

k = 1;

for bodyObject in displayPart.Bodies

A = bodyObject.GetUserAttribute("attribute", NXOpen.NXObject.AttributeType.String, -1)
A_value = A.StringValue
listA[k] = A_value
k = k+1;

So lets say that listA looks something like this now:

listA = ["1","5","8,"12"]

Now I want to associate a random number with each member of the listA and store it in a new dictionary so that I get something like this:

listB["1"] = 101

listB ["5"] = 303

listB["8"] = 10012

listB["12"] = 91

I think I may need some kind of for loop to cycle thru each ListA value and assign a new value in ListB. Something like this maybe...

j =  get size of listA

for 1 thru j

listB[" listA(j) "] = random.randit(....)

Do you guys have some insight that may be helpful as to how to accomplish this? Thanks in advance

Highlighted

# Re: NX11 Python Indexing Dictionary and Setting Random Numbers

Siemens Phenom

As shown in your pseudo code, listA is a list. listB is a dictionary.

You can use list comprehension and zip to generate this simply:

```from random import *

listA = [1,5,8,12]
listB = [randint(0,10000) for a in listA]
dictB = dict(zip(listA, listB))

print(listA)
print(listB)
print(dictB)```

output:

```[1, 5, 8, 12]
[5895, 23, 7465, 4147]
{1: 5895, 5: 23, 8: 7465, 12: 4147}```

Note that the intermediate listB is not really needed:

```from random import *

listA = [1,5,8,12]
dictB = dict(zip(listA, [randint(0,10000) for a in listA]))

print(listA)
print(dictB)```

output:

```[1, 5, 8, 12]
{1: 6761, 5: 3750, 8: 1403, 12: 2061}```