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])
Related
I have a string
str = "Name John"
I want to change it to a dictionary.
{"Name":"John"}
How do I achieve this?
I Have tried using comprehension but I get an error.
str = "Arjun 23344"
Name = {str.split()}
Error
Traceback (most recent call last):
File "/home/daphney/Python/AGame.py", line 2, in <module>
Name = {x.split()}
TypeError: unhashable type: 'list'
You can split:
my_dict = {str.split(" ")[0]:str.split(" ")[1]}
Note: If you have, say, Name John Smith and want the dict to be Name:Smith, then you can just change the [1] to [-1] to get the last indexed item.
You can create a dictionary using dict function by providing list of [key,value] lists (or (key,value) tuples):
my_str = "Arjun 23344"
Name = dict([my_str.split()])
print(Name) # output: {'Arjun': '23344'}
Name = dict([str.split()])
This would only work if your string always splits into exactly two words. This works because the split call returns a list of two elements, which is then stored inside a containing list, and passed to the dict constructor. The latter can work properly with a sequence (list or other) of pairs (lists or other).
This works in this particular case, but is not robust or portable.
As there are only two strings in your variable.
string = "Name Shivank"
k,v = string.split()
d = dict()
d[k] = v
print(d) #output: {'Name':'Shivank'}
you can provide a second parameter to the split function to limit the number of separations (to 1 in this case):
dict([string.split(" ",1)])
I've found several SO posts on similar questions but I'm maybe overthinking my problem.
I'm running a loop. Each iteration returns a dict with the same keys and their own values. I'd like to combine them into a new master dict.
On each loop iteration I can save the results to a list
store_response = [] # will store the results of each iteration here
myloop:
code here...
store_response.append(iresponse.copy())
Or I can do:
store_response = {} # will store the results of each iteration here
myloop:
code here...
store_response[page_token] = iresponse # store this iteration and call it whatever string page_token currently is
So I can return either a list of dicts or dict of dicts.
My question is, how can I combine them into just one dict?
Tried several for loops but keep hitting errors e.g.:
for d in store_response:
for key, value in d.iteritems():
test[key].append(value)
Traceback (most recent call last):
File "<input>", line 2, in <module>
AttributeError: 'dict' object has no attribute 'iteritems'
Here is how the variable looks in PyCharms variables pane, currently in list form but I could make it a dict:
How can I take each dict within store response and create a single master dict?
You could try a pattern like:
from collections import defaultdict
store_response = defaultdict(list)
for _ in loop:
# Assuming the loop provides the key and value
store_response[key].append(value)
This will result in a dict with one key that collapses all values for that key as a list (in your use case since your dictionaries only have one key - this solution works for arbitrarily many keys like 'reports').
You are using Python 3, and in Python 3 iteritems has been removed use items instead.
for d in store_response:
for key, value in d.items():
test.setdefault(key, [])
test[key].append(value)
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').
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])
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:]