简体   繁体   中英

How to get value from list of tuple?

I have a list below:

ma_list:

{'Short_windows': 1, 'Long_windows': 2, 'Cover_windows': 2}

But I can't use ma_list[0] to get Short_windows's value 1.

How to get Short_windows , Long_windows , Cover_windows's value?

If I try to print ma_list['Short_windows']

It will show errors below:

TypeError: list indices must be integers, not str

That's not a list , its a dict , and you need to access the values using the keys:

>>> d = {'Short_windows': 1, 'Long_windows': 2, 'Cover_windows': 2}
>>> d['Short_windows']
1

Alternatively:

>>> for key, value in d.items():
...     print key, value
... 
Short_windows 1
Long_windows 2
Cover_windows 2

You can use dic.get('key') to get a certain value.
But since dictionaries are not ordered there is no get.(index) method.
You can use an OrderedDic to keep the order of your elements.

The documentation for OrderedDic is here: https://docs.python.org/2/library/collections.html#collections.OrderedDict

Your ma_list is a dict , not list .

Since this being a dictionary, you can get value via keys :

ma_dict = {'Short_windows': 1, 'Long_windows': 2, 'Cover_windows': 2}
ma_dict['Short_windows'] = 1

Dictionaries are unordered in Python. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use ma_dict.keys()[0] and ma_dict.values()[0] or ma_dict.items()[0] .

If you do care about the order of the entries, starting with Python 2.7 you can use collections.orderdDict OR odict .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM