Reputation: 102
I'm trying to create a dictionary of the form:
{: [ , {}]}
For example:
d = {term: [number, {number1: number2}]}
I tried to create the dictionary inside but I'm new and I couldn't understand how it's possible. The problem is that I want the form of d and I want to update number or the dictionary that contains number1 as key and number2 as value when finding term.
So the question is: Is it possible to create a dictionary like d ? And if so, how can I access term, number and the inside dictionay?
Upvotes: 1
Views: 188
Reputation: 2407
d = {"term": [5, {6: 7}]}
The key's value is a list:
d["term"]
[5, {6: 7}]
The list 's 1st element:
d["term"][0]
5
The list 's second element is a dictionary:
d["term"][1]
{6: 7}
The value of the dictionary's key '6' is 7:
d["term"][1][6]
7
Edit: Some examples for modification:
d = {"term": [5, {6: 7}]}
d["term"].append(10)
print(d)
Out: {'term': [5, {6: 7}, 10]}
l=d["term"]
l[0]=55
print(d)
Out: {'term': [55, {6: 7}, 10]}
insidedict=l[1]
print(insidedict)
{6: 7}
insidedict[66]=77
print(d)
{'term': [55, {6: 7, 66: 77}, 10]}
Upvotes: 1
Reputation: 164693
Sure, just define it as you have:
d = {'term': [5, {6: 7}]}
Since your dictionary has just one key, you an access the key via:
key = next(iter(d))
You can then access the value 5
via a couple of ways:
number = d[key][0]
number = next(iter(d.values()))[0]
Similarly, you can access the inner dictionary via either:
inner_dict = d[key][1]
inner_dict = next(iter(d.values()))[1]
And repeat the process for inner_dict
if you want to access its key / value.
Upvotes: 1