In a large file the following being part of it, I need to add 1 in a loop to the second value (now set to 0) of certain keys, but I have not been able to find a way to do it:
[{'TCGA-KL-8331-01A-11D-2310-10': ('T>G ATG', 0)},
{'TCGA-KL-8331-01A-11D-2310-10': ('T>C CTA', 0)},
{'TCGA-KL-8343-01A-11D-2310-10': ('T>G TTG', 0)},
{'TCGA-KL-8343-01A-11D-2310-10': ('T>G GTC', 0)},
{'TCGA-KO-8417-01A-11D-2310-10': ('T>G TTA', 0)},
{'TCGA-KO-8417-01A-11D-2310-10': ('C>G GCA', 0)}]
If each dictionary is d, the code d.values()[1]+=1
gives the error 'dict_values' object does not support indexing
and by list(d.values())[0][1]+=1
I get 'tuple' object does not support item assignment
. Is there a way forward?
edit
Input file is tsv and this list is generated earlier in the script. I write, for example:
for m in linesList:
for n in patMutsList:
if m.keys()==n.keys() and list(m.values())[0][2]==list(n.values())[0][0]:
list(n.values())[0][1]+=1
If you have a function like this:
def increment_value(aDict):
item = next(iter(aDict.items()))
k,v = item
d,n = v
aDict[k] = d,n + 1
Then you can call it like this:
values = [ {'TCGA ...' # rest of list of dicts elided
increment_value(values[2])
print(value[2])
Output:
{'TCGA-KL-8343-01A-11D-2310-10': ('T>G TTG', 1)}
Update:
From your edit it seems that you are looping through values
above (You call them patMutsList
) and n
is the current item, so the instead of:
list(n.values())[0][1]+=1
You can call:
increment_value(n)
Although I like @quamrana's answer as it works for your data as is.
If possible you should try to load the data as a dict
and move from tuples
to lists
as tuples are immutable This is just going off the information provided. Assuming each dict
has one key like your example shown.
So your data would look like this:
data = {
'TCGA-KL-8331-01A-11D-2310-10': ['T>G ATG', 0],
'TCGA-KL-8331-01A-11D-2310-10': ['T>C CTA', 0],
'TCGA-KL-8343-01A-11D-2310-10': ['T>G TTG', 0],
'TCGA-KL-8343-01A-11D-2310-10': ['T>G GTC', 0],
'TCGA-KO-8417-01A-11D-2310-10': ['T>G TTA', 0],
'TCGA-KO-8417-01A-11D-2310-10': ['C>G GCA', 0]
}
This way you could change a value much easier using the following syntax:
key = 'TCGA-KL-8331-01A-11D-2310-10'
data[key][1] += 1
print(data[key])
#['T>G ATG', 1]
edit
If it isn't a troublesome rework, consider loading your data as a dict.
Consider taking a peek at this question.
Or if this is something better done after the data is loaded, using the following or a variation thereof:
def unpack_data(data):
unpacked = dict(_ for d in data for _ in d.items())
return({k: list(v) for k, v in unpacked.items()})
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.