-5

I want to create a dictionary in which each key will have names like doc1, doc2,....,doc2105 and it will store value from Title_Loans.documents[0],Title_Loans.documents[1],....,Title_Loans.documents[2104]. I am trying to run a for loop on length(Title_Loans.documents) inside a dictionary but it is showing error:

for i in range(len((Finance.documents)):
      ^
SyntaxError: invalid syntax

Below is the code I am running. Please suggest me how this can be done. Code: Sample:

docs = {
    'doc1': Title_Loans.documents[0],
    'doc2': Title_Loans.documents[1],
    'doc3': Title_Loans.documents[2],
    'doc4': Title_Loans.documents[3],
    'doc5': Title_Loans.documents[4]
}

Trying to run above code using for loop for large document size.

docs = {
for i in range(len((Finance.documents)):
    doc[i]: Finance.documents[i]
    }
akshat
  • 1,219
  • 1
  • 8
  • 24
Ankita Patnaik
  • 271
  • 1
  • 7

5 Answers5

4

If you need a dictionary comprehension then you have to use comprehension syntax, not a statement (comprehensions are expressions):

docs = {"doc"+str(i): Finance.documents[i]
        for i in range(len(Finance.documents))}

This would, however, be much better written as

docs = {"doc"+str(i): documt for (i, documt) in enumerate(Finance.documents)}

I am unsure, though, why a dict that can be accessed with keys like "doc1", "doc2", etc. is better than a simple list, which can be accessed with integer keys.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
0

Try:

for i in range(len(Finance.documents)):

for your invalid syntax error.

Xantium
  • 11,201
  • 10
  • 62
  • 89
0

If you want your keys to take the form "doc(num)" then create a string doc_format = "doc{}"

then run:

docs = {doc_format.format(index+1): Finance.documents[index] for index in range(len(Finance.documents))}

letroot
  • 276
  • 1
  • 4
  • 13
  • 1
    Or enumerate over the list: `docs = { doc_format.format(index+1): f for index, f in enumerate(Finance.documents)}` – ap91484 May 24 '18 at 13:10
0

You are not using the correct dict-comprehension syntax, it should be:

{key, value for key in your_iterable}

where, value can be some function of key or vice-versa

For your case:

docs = {"doc{}".format(i + 1): Finance.documents[i] for i in range(len(Finance.documents))}
akshat
  • 1,219
  • 1
  • 8
  • 24
0

You could try this as well,

doc = {}
for i in range(len(Finance.documents)):
   doc[i] = Finance.documents[i]
print(doc)
Narendra Prasath
  • 1,501
  • 1
  • 10
  • 20