'how to get the index of a table and store it python
dict_ = {'key 1': ['value 1', 'value 2'], 'key 2': ['value 1', 'value 2'], 'key 3': ['value 1', 'value 2']}
print(tabulate(dict_, headers='keys', showindex='always'))
OUTPUT :
key 1 key 2 key 3
-- ------- ------- -------
0 value 1 value 1 value 1
1 value 2 value 2 value 2
how do I insert a custom row index so that i can store and use said index
Solution 1:[1]
Consider using pandas.DataFrame
instead, which provides the type of index you are probably looking for. Otherwise if you want to restrict yourself to using dictionaries and you want an explicit "row count", just insert another "column" with e.g. 'index': list(range(len(my_column))
. Then i
in
dict_['key 1'][i]
is essentially the index value. Another option would be to store lists of tuples instead, like
'key 1': [(i, v) for i,v in enumerate(my_column)]
etc., where my_column
is one of the lists in your dictionary.
Solution 2:[2]
Please let me know if I misinterpreted the question.
In Python 3.6+ dictionaries are stored in the order they are given as input. So, if you add 'key 4' to the dictionary, it's index would be 3. So, in theory you could either just use this logic to calculate the index or store the index along in the value.
eg: 'key 1': ['value 1', 'value 2',0]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ctenar |
Solution 2 |