I am trying to iterate through a tuple of dictionaries using Python, get the value that I'm looking for and then modify another dictionary with that value. Example:
Dict = {'1': 'one', '2': 'three'}
Tuple = ({'1': 'one', '5': 'five'}, {'4': 'four', '2': 'two'})
My goal is to modify Dict
and replace 'three'
with 'two'
from my second dictionary in my tuple.
I know how to iterate through dictionaries using for loops and dict.items()
, but i can't seem to do so with tuple...
Any help will be much appreciated!
1 Answer 1
Just check each dict d
for the key and then set Dict["2"]
equal to d["2"]
.
Dict = {'1': 'one', '2': 'three'}
Tuple = ({'1': 'one', '5': 'five'}, {'4': 'four', '2': 'two'})
for d in Tuple:
if "2" in d:
Dict["2"] = d["2"]
If you have multiple dicts in Tuple that have the same key the value will be set to the last dict you encounter. If you wanted the first match you should break
in the if.
Dict = {'1': 'one', '2': 'three'}
Tuple = ({'1': 'one', '5': 'five'}, {'4': 'four', '2': 'two'})
for d in Tuple:
if "2" in d:
Dict["2"] = d["2"]
break # get first match
If you want the last match it would be better start at the end of Tuple:
for d in reversed(Tuple):
if "2" in d:
Dict["2"] = d["2"]
break # last dict in Tuple that has the key
-
i dont need two for loops on d?Froodo– Froodo2015年05月11日 14:59:20 +00:00Commented May 11, 2015 at 14:59
-
Seems unlikely that the OP literally just wants to replace items with key '2', can you clarify if this is the goal @Froodo?Max Spencer– Max Spencer2015年05月11日 15:00:18 +00:00Commented May 11, 2015 at 15:00
-
@Froodo, no,
if "2" in d
will see if the key exists in the dict, there is no need to iterate over the keys and it is actually less efficient .Padraic Cunningham– Padraic Cunningham2015年05月11日 15:00:20 +00:00Commented May 11, 2015 at 15:00 -
@MaxSpencer, that is irrelevant, the logic is what is important. They also commented stating they know the specific key they want to look for.Padraic Cunningham– Padraic Cunningham2015年05月11日 15:01:47 +00:00Commented May 11, 2015 at 15:01
-
@MaxSpencer, I already know what keys i need to replace everytime. I have a marker that defines that since i dont want to modify them everytime. :)Froodo– Froodo2015年05月11日 15:02:20 +00:00Commented May 11, 2015 at 15:02
Explore related questions
See similar questions with these tags.
Dict
have all of the key/value pairs from theTuple
dicts?Tuple
contains two dictionaries with a key that matches a key inDict
, for example:Tuple = ({'1': 'one', '5': 'five'}, {'4': 'four', '2': 'two'}, {'2': 'six'})
?