Reputation: 727
I am working on a python 2.7 script such that given an URL with certain number of key-value pairs (not fixed numer of them), retrieves this values on a json structure.
This is what I have done so far:
from furl import furl
url = "https://search/address?size=10&city=Madrid&offer_type=1&query=Gran%20v"
f = furl(url)
fields = ['size', 'city', 'offer_type', 'query']
l = []
l.append(f.args['size'])
l.append(f.args['city'])
l.append(f.args['offer_type'])
l.append(f.args['query'])
body = {
fields[0]: f.args[fields[0]],
fields[1]: f.args[fields[1]],
fields[2]: f.args[fields[2]],
fields[3]: f.args[fields[3]]
}
This code works, but just for the case in which I know that there will be 4 key-value pairs, and the names of those pairs. I do not know how to face the problem if, for example, my url is shorter or larger.
Using this command length = len(f.args)
I can obtain the number of pairs, but no idea of how to extract the key names from the f.args
object
Thank you very much, Álvaro
Upvotes: 2
Views: 2036
Reputation: 114440
The furl
library is not especially well documented, but digging through the source code shows that f.args
is a property that redirects eventually to an orderedmultidict.omdict
object. This supports all the standard dictionary methods, in addition to lots more interesting stuff (also not well documented).
You can therefore just use f.args
wherever you need body
. If you need a copy for some reason, do f.args.copy()
, or possibly dict(f.args)
.
Upvotes: 1
Reputation: 9010
I'm slightly confused... f.args
is already a dictionary-like object of the type you want. If you want to explicitly convert it to a dictionary, you can use:
body = dict(f.args)
But even this seems unnecessary. If you want a new copy of the object so that you can change it without affecting the original instance, you can call the .copy()
method.
Upvotes: 4
Reputation: 261
is this what you're looking for?
from furl import furl
url = "https://search/address?size=10&city=Madrid&offer_type=1&query=Gran%20v"
f = furl(url)
print zip(f.args.keys(),f.args.values())
Output:
[('size', '10'), ('city', 'Madrid'), ('offer_type', '1'), ('query', 'Gran v')]
Upvotes: 2