Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent for HashMap [duplicate]

Tags:

python

hashmap

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.

like image 437
Wolf Avatar asked Oct 25 '13 11:10

Wolf


People also ask

What is the equivalent of HashMap in Python?

In Python, dictionaries are examples of hash maps.

How does Python handle duplicate keys?

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.


1 Answers

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.

like image 172
Games Brainiac Avatar answered Oct 18 '22 04:10

Games Brainiac