Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to access first type of data

NumberTextSet3 = {"ten": 10, 
                  "hundred": 100,
                  "thousand": 1000,
                  "million": 1000000,
                  "billion": 1000000000,
                  "trillion": 1000000000000}

In this dictionary, I can access the number 1000000000000 by using NumberTextSet3["trillion"] . But how would I access the the last word in the dictionary, maybe like: NumberTextSet3[-1] and have it return "trillion"?

like image 380
Oliver Murfett Avatar asked Oct 31 '22 18:10

Oliver Murfett


2 Answers

There is no last word in a dictionary.

To check it, try,

print NumberTextSet3

You will get different ordered result in different time.

You can slightly modify your data structure to [("ten",10),("hundred",100),...]

Now, you can use it with index.

For example,

a=[("ten",10),("hundred",100)]

print a[0][0]
print a[1][1]

Output:

ten
100

You can use an OrderedDict too

like image 147
Ahsanul Haque Avatar answered Nov 02 '22 22:11

Ahsanul Haque


I would use a OrderedDict like this:

from collections import OrderedDict

NumberTextSet3 = OrderedDict([("ten", 10),
                              ("hundred", 100),
                              ("thousand", 1000),
                              ("million", 1000000),
                              ("billion", 1000000000),
                              ("trillion", 1000000000000)])
# On Python2 this will work:
print NumberTextSet3.keys()[-1]
# This is a little bit longer but will work in Python2 and Python3:
print list(NumberTextSet3.keys())[-1]
like image 31
Salo Avatar answered Nov 02 '22 23:11

Salo