I'm new to python. I have a directory which has many subfolders and files. So in these files I have to replace some specified set of strings to new strings. In java I have done this using HashMap
. I have stored the old strings as keys and new strings as their corresponding values. I searched for the key in the hashMap and if I got a hit, I replaced with the corresponding value. Is there something similar to hashMap in Python or can you suggest how to go about this problem.
To give an example lets take the set of strings are Request, Response. I want to change them to MyRequest and MyResponse. My hashMap was
Key -- value
Request -- MyRequest
Response -- MyResponse
I need an equivalent to this.
In Python, dictionaries are examples of hash maps.
You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With