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!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.