I think this is a basic question, but I want to know this.
For example, in the below situation:
str1 = {}
str1['a'] = 1
str1['b'] = 2
I want to access to the following value:
str1['a'][0]
I think i've solved it.
I could use it this way. when i got a key, check the key and can make a list.
Sorry for confusing..
import sys
key='a'
str1={}
if 'a' in str1.keys():
str1['a'].append(0)
else:
str1 = {key : list()}
str1['a'].append(0)
print(str1['a'][0])
str1['a'].append(3)
print(str1['a'])
Sang Yoon Kim;
I think you might be confusing nested lists with Dictionaries
Dictionary is a key value pair.
Take a look at this;
L = [1,2,3] ----> L[0] = 1
G = [[1,2,3],[4,5,6]]
Now G[1] gives a list [4,5,6]
to access the element 6 , do G[1][2]
Dictionaries are entirely different
Please take a look at these links;
https://www.geeksforgeeks.org/python-list/
https://www.geeksforgeeks.org/python-dictionary/
To answer you question, you cannot access str['a][0] because its an invalid operation.
I think i've solved it. I could use it this way. when i got a key, check the key and can make a list. Sorry for confusing..
import sys
key='a'
str1={}
if 'a' in str1.keys():
str1['a'].append(0)
else:
str1 = {key : list()}
str1['a'].append(0)
print(str1['a'][0])
str1['a'].append(3)
print(str1['a'])
Related
So if you have some dictionary like this
dictionary={}
dictionary['a']=1
dictionary['a']=2
print(dictionary)
this would print {'a':2} and replaces the 1
Is there any way I can add 2 to the key 'a' as a list ?
I know i can do something this like:
dictionary['a']=[1,2]
but I don't want to do it like this.
Essentially what i am asking is how can i add the new value to my key using a list instead of replacing the previous value.
Appreciate the help!
dictionary = {}
dictionary['a'] = []
dictionary['a'].append(1)
dictionary['a'].append(2)
print(dictionary)
It would be worth considering using a defaultdict if every value in the dict is/will be a list:
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
Hello Stack Overflow,
What is the most readable + simplest way to get a value from a dictionary that only contains one key-value pair?
Note: I do not know what the key is when I try to fetch the value, it's autogenerated.
Let's imagine the dictionary to look something like this:
my_dict = {
"unknown_key_name": 1
}
FYI I am using Python 3.6. My current solution is this: val = list(my_dict.values())[0]
I just have a feeling there is a more "elegant" solution, does anyone know of one?
Get the iterator for values then use the next call to get the first value:
my_dict = {
"unknown_key_name": 1
}
first_val = next(iter(my_dict.values()))
print(first_val) # 1
This won't put a list into memory just to get the first element.
Use name, value = my_dict.popitem()
>>> my_dict = {"unknown_key_name": 1}
>>> name, value = my_dict.popitem()
>>> name
'unknown_key_name'
>>> value
1
>>>
I have a function below which searches for a dictionary key match using an inputted function parameter. If a key match is found I want the value at index 1 (the team) to change to the desired team inputted when the function is called:
dict1 = {'Messi' : ('Argentina','Barcelona'), 'Ronaldo' : ('Portugal','Juventus'), 'Robben': ('Netherlands','Bayern')}
def setNewTeam(plyr, newTeam):
for x in dict1:
if plyr == x:
dict1[plyr][1] = newTeam
setNewTeam('Messi', 'Manchester')
When I run this code however, I get:
TypeError: 'tuple' object does not support item assignment
I know this must be because tuples are not mutable but there must be a way of making this work since i'm working with dictionaries, can anyone lend a hand here?
Thank you!
As the error message says, you cannot assign new items to tuples because tuples are immutable objects in python.
my_tup = (1,2,3)
my_tup[0] = 2 # TypeError
What you could do is using a list instead:
dict1 = {'Messi' : ['Argentina','Barcelona'], 'Ronaldo' : ['Portugal','Juventus'], 'Robben': ['Netherlands','Bayern']}
def setNewTeam(plyr, newTeam):
for x in dict1:
if plyr == x:
dict1[plyr][1] = newTeam
setNewTeam('Messi', 'Manchester')
Note how lists are created using [] while tuples use ().
dict1 = {'Messi' : ('Argentina','Barcelona'), 'Ronaldo' : ('Portugal','Juventus'), 'Robben': ('Netherlands','Bayern')}
def setNewTeam(plyr, newTeam):
for x in dict1:
if plyr == x:
dict1[plyr] = (dict1[plyr][0], newTeam)
setNewTeam('Messi', 'Manchester')
Since you want to update values, tuple is not the good data-structure. You should use a list.
If you still want to use a tuple, you can build a brand new tuple with :
dict1[plyr] = (dict1[plyr][0], newTeam)
dict1[plyr][1] = newTeam
Tuples are immutable, but lists are not. You can do something like:
list1 = list(dict1[plyr])
list1[1] = newTeam
dict1[plyr] = tuple(list1)
It will add the newTeam to your desired location, and it will still be a tuple.
This is for a python project I'm working on. I'm still learning the language, but I have hit a stump here. Any help is greatly appreciated. Here is my pseudo code:
variable1 = (returned function() value)
listItem = []
<start loop>
If value of variable1 IS NOT in listItem:
listItem.append(assign value from variable1)
else:
go back to start of loop
print listItem(all items)
I am confused if its best to use a for, while, or if statement here. I have tried with all three, but I get various errors. I am not seeing something...
You want to convert a list to a unique list:
>>> results = function()
>>> unique = []
>>> for result in results:
... if result not in unique:
... unique.append(result)
set is good for uniqueness, and you can convert it to a list easily:
>>> unique = list(set(results))
However, this won't keep the order of the original results.
Python doesn't have an ordered set, but it does have an ordered dictionary, which you can abuse by using it's keys as an ordered set:
>>> from collections import OrderedDict
>>> ordered_unique = OrderedDict((key, key) for key in results).keys()
Currently all you need is the if statement, you don't need the loop or the else statement.
If I understand you correctly, you want to search listItem for ONE variable (variable1), and if it doesn't contain that variable, you want to append it to the list. However, it seems like your question is missing something. Perhaps you are trying to search listItem for multiple variables?
Thanks for the insight everyone. I have figured it out. I needed to use a while loop for this task. Here is my solution.
variable0 = <null value>
listItem = [empty list]
variable1 = 0 (required for while loop expression)
while variable1 is less than 0:
variable0 = (returned random function() value)
if variable0 is not in listItem:
Append variable0 value to listItem
increase value of variable1 by 1
print contents of listItem
Thanks again for all of your help.
I have a case where I need to construct following structure programmatically (yes I am aware of .setdefault and defaultdict but I can not get what I want)
I basically need a dictionary, with a dictionary of dictionaries created within the loop.
At the beginning the structure is completely blank.
structure sample (please note, I want to create an array that has this structure in the code!)
RULE = {
'hard_failure': {
4514 : {
'f_expr' = 'ABC',
'c_expr' = 'XF0',
}
}
}
pseudo code that needs to create this:
...
self.rules = {}
for row in rows:
a = 'hard_failure'
b = row[0] # 4514
c = row[1] # ABC
d = row[2] # XF0
# Universe collapse right after
self.rules = ????
...
The code above is obviously not working since I dont know how to do it!
Example, that you've posted is not a valid python code, I could only imagine that you're trying to do something like this:
self.rules[a] = [{b:{'f_expr': c, 'c_expr': d}}]
this way self.rules is a dictionary of a list of a dictionary of a dictionary. I bet there is more sane way to do this.
rules = {}
failure = 'hard_failure'
rules[failure] = []
for row in rows:
#this is what people are referring to below. You left out the addition of the dictionary structure to the list.
rules[failure][row[0]] = {}
rules[failure][row[0]]['type 1'] = row[1]
rules[failure][row[0]]['type 2'] = row[2]
This is what I created based on how I understood the questions. I wasn't sure what to call the 'f_expr' and 'c_expr' since you never mention where you get those but I assume they are already know column names in a resultset or structure of some sort.
Just keep adding to the structure as you go.
Your example code doesn't seem to be valid Python. It's not clear if the second level element is supposed to be a list or a dictionary.
However, if you're doing what I think you're doing, and it's a dictionary, you could use a tuple as a key in the top-level dictionary instead of nesting dictionaries:
>>> a = 'hard_failure'
>>> b = 4514
>>> c = "ABC"
>>> d = "XF0"
>>> rules = {}
>>> rules[(a,b)] = {'f_expr' : a,'c_expr' : d}
>>> rules
{('hard_failure', 4514): {'c_expr': 'XF0', 'f_expr': 'hard_failure'}}
My favorite way to deal with nested dictionaries & lists of dictionaries is to use PyYAML. See this response for details.
Well, I apologize for the confusion, I never claimed that code actually compiled, hence (pseudo). Arthur Thomas put me on the right track, here is slightly modified version. (Yes, now its a simply nested dictionary, 3 levels down)
RULE_k = 'hard_failure'
self.rules = {}
for row in rows:
self.rules_compiled.setdefault(RULE_k, {})
self.rules_compiled[RULE_k][row[1]] = {}
self.rules_compiled[RULE_k][row[1]]['f_expr'] = row[0]
self.rules_compiled[RULE_k][row[1]]['c_expr'] = row[1]