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])
I have a dictionary in this format:
my_dict = {"key1":["value1", "value2", "value3"]}
Is there an easy way to get key1's third value?
I guess I could get the whole list of values and then split it up, but there must be a better way
You can do a simple look up in the following ways -
my_dict['key1'][2]
#Output = 'value3'
OR (using dict.get)
my_dict.get('key1')[2]
#Output = 'value3'
OR (if you want 3rd element without specifying the key)
list(my_dict.values())[0][2]
#Output = 'value3'
OR (if you want last element without specifying the key)
list(my_dict.values())[0][-1]
#Output = 'value3'
my_dict['key1'][2]
You access the list in. the value like any other list
I prefer to use get i.e. my_dict.get('key1')[2]
If you use my_dict['key1'][2] , you will get a KeyError if key1 is not present in my_dict
Example -
>>> d = {1:3,4:6}
>>> d.get(7) # No Error
>>> d[7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 7
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])
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
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:]