1

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.

1
  • The keys in this case will be strings unless converted - maybe they should be numbers? Commented Nov 24, 2013 at 19:49

2 Answers 2

1

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.'}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

why? If data is iterable, there's no need to do this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.