I'm not sure I understand exactly what it is you're trying to do :)
It looks like you're generating 3 values at a time and want to append them to the list at each iteration. Am I right?
You can do this very easily with the list.extend method. Assuming PyDisplace looks like the code below. I'm guessing PyDisplace is a dictionary containing a list of 3 elements pr key, so I've used some bogus data to show the idea. Please update your question if I'm way off :)
PyDisplace = {
1: [10, 20, 30],
2: [40, 50, 60],
3: [70, 80, 90],
}
OldDisplace = {
1: [1, 2, 3],
2: [4, 5, 6],
3: [7, 8, 9],
}
R_D = [] # or 'list()' if you will
keys = PyDisplace.keys()
keys.sort()
for val in keys:
DX = PyDisplace[val][0] - OldDisplace[val][0]
DY = PyDisplace[val][2] - OldDisplace[val][3]
DZ = PyDisplace[val][2] - OldDisplace[val][2]
# at each iteration, R_D will be extended with
# three new elements: DX, DY, DZ
R_D.extend([DX, DY, DZ])
print R_D
**Output**
In [71]: print R_D
-------> print(R_D)
[9, 18, 27, 36, 45, 54, 63, 72, 81]
So how does this differ from what you're doing?
Well for one, R_D is a list() instead of a dict(). Lists in python are usually 1-dimensional so it would seem a better fit for your problem here. Also, I'm extending the list with another list at every iteration.
Another way to traverse a dictionary is to use the dict.iteritems method. That way you can iterate over the key-value pairs like so:
for k,v in PyDisplace.iteritems():
print "key: %s, value: %s" % (k, v)
**Output:**
key: 1, value: [10, 20, 30]
key: 2, value: [40, 50, 60]
key: 3, value: [70, 80, 90]
EDIT:
thanks. it seems like the first one is well suited for me at this
point. again i am new to Python. eventually i will learn a lot and in
that sense the second method is quite not easy to get. which means i
need to a lot about Python. i will stdu the key words you mention like
"dict.iteritems", etc....thanks again. – user1678622 2 hours ago
Well what dict.iteritems() does, is somewhat the same as dict.keys() does, which you already know how to iterate over. Let's consider a simpler example, dict.items()
dict.items() returns a complete list of 2-tuples of all the key-value pairs in the dictionary, the same way dict.keys() return a finite list of keys. You can iterate over it like this:
for key, value in dictionary.items():
print "key: %s\nvalue: %s" % (key, value)
The difference is, dict.iteritems() returns an iterable object which you can... iterate through. To the for loop it's the same, but under the hood, the list is returned one item at a time, instead of built in one step which may be slow for big dictionaries for instance. I hope that cleared up some of the fuzz :)?