-2

I have this code:

dict = {
    "key": "0"
}

And I am reading some proxies from a file. Basically, I am updating dict['key'] with every single proxy. Resulting in

"key": ['proxy1','proxy2'...]

But when I make a request, I have this:

for x in range(0,l):
    requests.get(link, proxies=proxies[x])

The error I am getting is:

File "main.py", line 19, in (module)
request.get(link, proxies=dict['key'][x])
Key Error: 0

Doing proxies['http'][x] gives me the "str object has no attribute 'get' ".

It seems that it cannot make one request with each proxy.

Any help would be appreciated.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Benjamin
  • 315
  • 2
  • 14
  • Don't use `dict` as a variable name, you are masking the built-in. You want a *list* as the value. – Martijn Pieters May 24 '14 at 21:26
  • It sounds like you want your value to be a `list`. – juanchopanza May 24 '14 at 21:26
  • What 'values' do you want to assign to all these 'keys'? – Prophet May 24 '14 at 21:29
  • Make the value a list. Check [this](http://stackoverflow.com/questions/20585920/how-to-add-multiple-values-to-a-dictionary-key-in-python) on how can you implement this. – Syed Farjad Zia Zaidi May 24 '14 at 21:29
  • What is `request` here, what is `proxies`? You need to provide more context. The `Key Error` message looks.. incorrect at best. Your traceback doesn't match your actual code. – Martijn Pieters May 24 '14 at 21:39
  • Really, your question is now about something entirely unrelated, it seems. `proxies['http'][x]` is unrelated and something entirely different from `dict['key'][x]`, which is being used as the `proxies` keyword argument to a `.get()` method. – Martijn Pieters May 24 '14 at 21:42
  • When you present us with error messages, you need to include the **full traceback**, and preferably enough information of us to reproduce your error. – Martijn Pieters May 24 '14 at 21:58

2 Answers2

2

You want a list:

dct = {'key': []}

for i in range(10):
    dct['key'].append(i)

This is simply manipulating the list value associated with the key. The dictionary itself doesn't really change, it is only used to reference the contained list.

Whenever you need more than one value per key, you need a nested structure. Here it's a list, but it could be another dictionary, a tuple, a set, instances of a custom class, etc.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

If you want to avoid having to manually add the empty lists, use a defaultdict:

from collections import defaultdict
dd = defaultdict(list) # list if a nullary callable that returns a new list object
dd['var'].extend(range(10))
o11c
  • 15,265
  • 4
  • 50
  • 75