简体   繁体   中英

How to get integer from list and construct hash table in Python?

New to python. I have a tuple variable containing some information and i convert it into list. When I print each data element out by using my for loop, I got.

for data in myTuple:
    print list(data)

['1', " This is the system 1 (It has been tested)."]
['2', ' Tulip Database.']
['3', ' Primary database.']
['4', " Fourth database."]
['5', " Munic database."]
['6', ' Test database.']
['7', ' Final database.']

The problem is how I get the the number (which is in single quote/double quotes) and store it in a dictionary as below:

{’1’: 'This is the system 1 (It has been tested).', ’2’: 'Tulip Database.', ...}

Thank you.

Use dict() :

my_dict = dict(myTuple)

Demo:

>>> x = ([1, 'spam'], [2, 'foobar'])
>>> dict(x)
{1: 'spam', 2: 'foobar'}

dict() when passed an iterable does something like this(from help(dict) ) :

dict(iterable) -> new dictionary initialized as if via:
    d = {}
    for k, v in iterable:
        d[k] = v

As pointed out by JBernardo, you could use the builtin dict() .

You can also use a dictionary comprehension!

myTuple = [['1', " This is the system 1 (It has been tested)."],
           ['2', ' Tulip Database.']]
print {key:value for key, value in myTuple}

Output

{'1': ' This is the system 1 (It has been tested).', '2': ' Tulip Database.'}

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