How do I unpack a list with fewer variables? - python

k = [u'query_urls', u'"kick"', u'"00"', u'msg=1212', u'id=11']
>>> name, view, id, tokens = k
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
I need to provide 5 variables to unpack this list. Is there a way to unpack with fewer, so that tokens gets the rest of the list. I don't want to write another line to append to a list....
Thanks.
Of course I can slice a list, assign individually, etc. But I want to know how to do what I want using the syntax above.

In Python 3 you can do this: (edit: this is called extended iterable unpacking)
name, view, id, *tokens = k
In Python 2, you will have to do this:
(name, view, id), tokens = k[:3], k[3:]

Related

accessing nested dictionaries when you know the nested key?

This one is probably pretty easy, but I can't figure it out! Suppose I have a dictionary with a nested dictionary, that I know the nested dictionary key that I can store in a variable, how would I access this value?
k = 'mynested'
nestedk = 'blah'
x = {}
x['mynested'] = {}
x['mynested']['blah'] = 1
print(x[k[nestedk]])
throws error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
There is a slight mistake in your last line print(x[k[nestedk]]). This line actually means that you are treating the k variable as a list which is actually a string and the characters of the string can only be accessed by an integer index and not by a string index.
Change the last line to the below
print(x[k][nestedk])
You can get it with x[k][nestedk]. You can access the values similar to assigning values inside dictionary. As you are assigning
X[k] = {}
and x[k][nestedk] = 1
The value is 1 and key for nested object is k so initially we get the inner dictionary by x[k] and then we get the value using nested key in your case nestedk.
Thus you have to correct your print statement like below
print(x[k][nestedk])

How to get values from a list of dictionary?

How to get the values from a list of dictionary??
For example: I want to get the output as 2?
data = [{'a':1,'b':2,'c':3}]
Below is the error am observing.
data['b']
Traceback (most recent call last):
File "", line 1, in
data['b']
TypeError: list indices must be integers, not str
The dictionary is the first element in data, so you can access it with:
data[0]['b']
If you have multiple dictionaries and you aim want to use them in a fallback order, you can use:
def obtain_value(list_of_dicts,key):
for dict in list_of_dicts:
if key in dict:
return dict[key]
raise KeyError('Could not find key \'%s\''%key)
and then call it with obtain_value(data,'b').

converting tuple to dictionary in python

I am trying to convert a line of string to dictionary where i am facing an error.
here is what i have and what i did:
line="nsd-1:quorum"
t=tuple(line.split(":"))
d=dict(t)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
d=dict(t)
ValueError: dictionary update sequence element #0 has length 5; 2 is required
Basically, what i want to achieve is to have a key value pair.
So if i have set of values separated by a ":", i want to have it as a key whatever is before the colon and after the colon needs to be the value for the key.
example: if i take the above string, i want "nsd-1" as my key and "quorum" as value.
Any help is appreciated.
Thanks
Wrap it in a list:
>>> dict([t])
{'nsd-1': 'quorum'}
There's also no need to convert the return value of split to a tuple:
>>> dict([line.split(':')])
{'nsd-1': 'quorum'}
Put t inside an empty list, like this:
d=dict([t])

ValueError: too many values to unpack

I am trying to sort dictionaries in MongoDB. However, I get the value error "too many values to unpack" because I think it's implying that there are too many values in each dictionary (there are 16 values in each one). This is my code:
FortyMinute.find().sort(['Rank', 1])
Anyone know how to get around this?
EDIT: Full traceback
Traceback (most recent call last):
File "main.py", line 33, in <module>
main(sys.argv[1:])
File "main.py", line 21, in main
fm.readFortyMinute(args[0])
File "/Users/Yih-Jen/Documents/Rowing Project/FortyMinute.py", line 71, in readFortyMinute
writeFortyMinute(FortyMinData)
File "/Users/Yih-Jen/Documents/Rowing Project/FortyMinute.py", line 104, in writeFortyMinute
FortyMinute.find().sort(['Rank', 1])
File "/Users/Yih-Jen/anaconda/lib/python2.7/site-packages/pymongo/cursor.py", line 692, in sort
self.__ordering = helpers._index_document(keys)
File "/Users/Yih-Jen/anaconda/lib/python2.7/site-packages/pymongo/helpers.py", line 65, in _index_document
for (key, value) in index_list:
ValueError: too many values to unpack
You pass the arguments and values in unpacked as so:
FortyMinute.find().sort('Rank', 1)
It is only when you're passing multiple sort parameters that you group arguments and values using lists, and then too you must surround all your parameters with a tuple as so:
FortyMinute.find().sort([(Rank', 1), ('Date', 1)])
Pro-tip: Even the Cursor.sort documentation linked below recommends using pymongo.DESCENDING and pymongo.ASCENDING instead of 1 and -1; in general, you should use descriptive variable names instead of magic constants in your code as so:
FortyMinute.find().sort('Rank',pymongo.DESCENDING)
Finally, if you are so inclined, you can sort the list using Python's built-in as the another answerer mentioned; but even thought sorted accepts iterators and not just sequences it might be more inefficient and nonstandard:
sorted(FortyMinute.find(), key=key_function)
where you might define key_function to return the Rank column of a record.
Link to the official documentation
If you want mong/pymongo to sort:
FortyMinute.find().sort('Rank', 1)
If you want to sort using multiple fields:
FortyMinute.find().sort([('Rank': 1,), ('other', -1,)])
You also have constants to make it more clear what you're doing:
FortyMinute.find().sort('Rank',pymongo.DESCENDING)
If you want to sort in python first you have to return the result and use a sorting method in python:
sorted(FortyMinute.find(), key=<some key...>)

How to extract data using json in python

I have an issue with a code I've written. When I run the code I get an error :
Traceback (most recent call last):
File "test23_json_users.py", line 23, in <module>
for user_dict in abc['user_account']['sip_id']:
TypeError: list indices must be integers, not str
The code:
result = '[{"user_account":[{"address":null,"name":null,"country":null,"password":"****","extension":"1112","sip_id":"23001#50.50.50.201","sip_name":"23001","user_id":7973712,"locked":false,"created":null,"h323_name":"1101","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1113","sip_id":"23002#50.50.50.201","sip_name":"23002","user_id":8847075,"locked":false,"created":null,"h323_name":"1102","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1114","sip_id":"23003#50.50.50.201","sip_name":"23003","user_id":3680630,"locked":false,"created":null,"h323_name":"1103","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1115","sip_id":"23004#50.50.50.201","sip_name":"23004","user_id":136391,"locked":false,"created":null,"h323_name":"1104","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1116","sip_id":"23005#50.50.50.201","sip_name":"23005","user_id":5692227,"locked":false,"created":null,"h323_name":"1105","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1117","sip_id":"23006#50.50.50.201","sip_name":"23006","user_id":7559026,"locked":false,"created":null,"h323_name":"1106","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1118","sip_id":"23007#50.50.50.201","sip_name":"23007","user_id":3226075,"locked":false,"created":null,"h323_name":"1107","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1119","sip_id":"23008#50.50.50.201","sip_name":"23008","user_id":6184875,"locked":false,"created":null,"h323_name":"1108","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1120","sip_id":"23009#50.50.50.201","sip_name":"23009","user_id":1711112,"locked":false,"created":null,"h323_name":"1109","city":null,"email":null,"phone":null,"zip":null},{"address":null,"name":null,"country":null,"password":"****","extension":"1121","sip_id":"23010#50.50.50.201","sip_name":"23010","user_id":5383101,"locked":false,"created":null,"h323_name":"1110","city":null,"email":null,"phone":null,"zip":null}]}'
params = result[result.find('{"'):]
#print params
abc = json.loads(params)
# Here I'm trying to extract just sip_id from the string result using json.
# I am not able to figure out what went wrong .
for user_dict in abc['user_account']['sip_id']:
print 'usersname : %s' % (user_dict['sip_id'])
Change
for user_dict in abc['user_account']['sip_id']:
to
for user_dict in abc['user_account']:
abc['user_account'] is supposed to be a list.
A list a=['hello',1,2,'people'] has 4 elements accessed by indexes a[0] through a[3].
A dictionary d={'a':1,'b':2} has keys and values. In this case d['a'] has value 1, d[b'] has 2.
If you want to access something in abc['user_account'], type abc['user_account'][42]. If you want to iterate over it
for a in abc['user_account']:
print a

Categories

Resources