I'm kind of new to python and need some help. I was planning on having some sort of a hashMap-kind-of data structure to map a string to its length. How do I do this in python?
Asked
Active
Viewed 3,581 times
0
-
2https://docs.python.org/2/tutorial/datastructures.html#dictionaries. There's not much point here, though, as `len(s)` is `O(1)` - see http://stackoverflow.com/q/1115313/3001761 – jonrsharpe Mar 17 '15 at 16:40
-
possible duplicate of [Add to a dictionary in Python?](http://stackoverflow.com/questions/1024847/add-to-a-dictionary-in-python) – motoku Mar 17 '15 at 16:45
-
Important question is to ask why you want to do this, you might be running into a classic XY problem here... http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – shuttle87 Mar 17 '15 at 16:49
1 Answers
3
Use an empty dictionary, like so:
string_lengths = {}
string = 'hello'
string_lengths[string] = len(string)
print string_lengths
Output:
{'hello': 5}
Or do this for a list of strings:
string_lengths = {}
strings = ['Hello', 'There', 'Human Being']
for x in strings:
string_lengths[x] = len(x)
print string_lengths
Output:
{'Human Being': 11, 'There': 5, 'Hello': 5}
Note that Dictionaries are unordered lists of key, value pairs.
To Reference the items in a dictionary:
string_lengths['Hello']
returns 5

MikeVaughan
- 1,441
- 1
- 11
- 18