Reputation: 963
I'm working on a program where the user inputs 3 values (one of which is in dictionary notation form).. but I'm having trouble finding out how to work with this special notation.
The user input will look like this:
{'X':'X+YF','Y':'FX-Y'}
which I store in a variable p
. I know that with p.keys()
I get ['X', 'Y']
and with p.values()
I get ['X+YF', 'FX-Y']
.
How can I relate 'X'
to 'X+YF'
to say, if the value of the first key in p
is 'X'
, store 'X+YF'
in a var, and if the value of the second key in p
is 'Y'
, store 'FX-Y'
in a var?
Is something like this also possible with the same approach stated in the answers below?
If x is found in some string :
swap out the X with the value p['X']
Upvotes: 0
Views: 2181
Reputation: 76254
Are you asking how to get the value associated to a particular key? You can acess a value by putting its key in square brackets:
myDict = {'X':'X+YF','Y':'FX-Y'}
myXVal = myDict['X']
myYVal = myDict['Y']
print myXVal, myYVal
output:
X+YF FX-Y
If you want to have different behavior based on which keys exist in the dict, you can use in
:
if 'X' in myDict:
#do some stuff with myDict['X'] here...
Edit in response to OP's edit: My psychic debugging powers tells me that you're trying to implement an L System. You need to replace all instances of 'X' with 'X+YF', and all instances of 'Y' with 'FX-Y'. I would implement the function like this:
#path is the string that you want to do replacements in.
#replacementDict is the dict containing the key-value pairs mentioned in your post.
def iterateLSystem(path, replacementDict):
#strings aren't mutable, so we make a mutable list version of path
listPath = list(path)
for i in range(len(listPath)):
currentChar = listPath[i]
if currentChar in replacementDict:
listPath[i] = replacementDict[currentChar]
#glob listPath back into a single string
return "".join(listPath)
Upvotes: 3
Reputation: 2769
You can walk over the dictionary using its .items()
method:
for key, value in p.items():
print key, value
# X X+YF
# Y FX-Y
# …
Upvotes: 3
Reputation: 8356
You can use .items()
or .iteritems()
to walk through the pairs:
>>> p = {'X':'X+YF','Y':'FX-Y'}
>>> for k, v in p.iteritems():
... print k, v
...
Y FX-Y
X X+YF
If you want to check the existence of some key, use in
keyword:
>>> 'X' in p
True
>>> if 'Y' in p:
... print p['Y']
...
FX-Y
Upvotes: 2
Reputation: 391982
p = {'X':'X+YF','Y':'FX-Y'}
var = p['X']
Is that what you're looking for?
Upvotes: 1