0

I'm new to Python. I need a data structure to contain a tuple of two elements: date and file path. I need to be able to change their values from time to time, hence I'm not sure a tuple is a good idea as it is immutable. Every time I need to change it I must create a new tuple and reference it, instead of really changing its values; so, we may have a memory issue here: a lot of tuples allocated.

On the other hand, I thought of a list , but a list isn't in fixed size, so the user may potentially enter more than 2 elements, which is not ideal.

Lastly, I would also want to reference each element in a reasonable name; that is, instead of list[0] (which maps to the date) and list[1] (which maps to the file path), I would prefer a readable solution, such as associative arrays in PHP:

tuple = array()
tuple['Date'] = "12.6.15"
tuple['FilePath] = "C:\somewhere\only\we\know"

What is the Pythonic way to handle such situation?

Mario Cervera
  • 671
  • 1
  • 8
  • 19
JavaSa
  • 5,813
  • 16
  • 71
  • 121

2 Answers2

3

Sounds like you're describing a dictionary (dict)

# Creating a dict
>>> d = {'Date': "12.6.15", 'FilePath': "C:\somewhere\only\we\know"}

# Accessing a value based on a key
>>> d['Date']
'12.6.15'

# Changing the value associated with that key
>>> d['Date'] = '12.15.15'

# Displaying the representation of the updated dict
>>> d
{'FilePath': 'C:\\somewhere\\only\\we\\know', 'Date': '12.15.15'}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • But isn't dictionary an overkill for this? I have only two parameters to store – JavaSa Jun 17 '15 at 20:10
  • Why would it be overkill? It's very light to create and modify. – Cory Kramer Jun 17 '15 at 20:13
  • Not in the way to build it , its easy, I meant when I'm thinking of dictionary I'm thinking of some hash table or map, which are related to solving more complex problems, and definitely having more keys and values to store than just two poor values – JavaSa Jun 17 '15 at 20:16
  • 1
    You are exactly correct, [a Python `dict` is in fact a hash map](https://stackoverflow.com/questions/114830/is-a-python-dictionary-an-example-of-a-hash-table). I wouldn't say just because there aren't a lot of elements that it is any more complex. If it solves the issue, then it is exactly the right container :) – Cory Kramer Jun 17 '15 at 20:19
2

Why not use a dictionary. Dictionaries allow you to map a 'Key' to a 'Value'. For example, you can define a dictionary like this:

dict = { 'Date' : "12.6.15", 'Filepath' : "C:\somewhere\only\we\know"}

and you can easily change it like this:

dict['Date'] = 'newDate'

Danny Dircz
  • 90
  • 11