I have a dict I want to iterate through to find all values that contain the key. My output would be a separate dict that would contain the numbers from each dict value without the key in the value or each specific keys values in the final
dict_in =
{'6': ['2,9,8,10'], '1': ['3,5,8,9,10,12'], '4': ['2,5,7,8,9'], '2': ['3,4,7,6,13'], '12': ['1,7,5,9'], '3': ['9,11,10,1,2,13'], '10': ['1,3,6,11'], '5': ['4,1,7,11,12'], '13': ['2,3'], '8': ['1,6,4,11'], '7': ['5,2,4,9,12'], '11': ['3,5,10,8'], '9': ['12,1,3,6,4,7']}
so the output would be like this:
{'6':['3,4,7,13,1,3,11,1,4,11,12,1,3,4,7'] , '4':['3,4,6,13,1,11,12,1,6,11,12,12,1,3,6'],'13': ['4,7,6,9,11,10,1']}
I am a beginner and I do not even know where to start. Would it be easier to convert it to a list of lists?
There is one thing about your problem that is an extra challenge. That is for you or some other good samaritan to solve. This is just a nudge in your direction. Your values for the keys is actually a single string. Now if it was actual integers, the problem is not too complicated. Also to note, your expected output that you wrote based on your requirement is actually typed wrong, you missed a few values.
In case of having integers instead of a string, I can show you one approach that as a beginner you can hopefully understand:
dict_in = {'6': [2,9,8,10], '1': [3,5,8,9,10,12], '4': [2,5,7,8,9], '2': [3,4,7,6,13], '12': [1,7,5,9], '3': [9,11,10,1,2,13], '10': [1,3,6,11], '5': [4,1,7,11,12], '13': [2,3], '8' :[1,6,4,11], '7': [5,2,4,9,12], '11': [3,5,10,8], '9': [12,1,3,6,4,7]}
dict_out = {}
for key in dict_in:
if key == "6" or key == "4" or key == "13":
for k,v in dict_in.items():
for y in v:
if int(key) in v and y != int(key):
dict_out.setdefault(key, []).append(y)
Output:
{'6': [3, 4, 7, 13, 1, 3, 11, 1, 4, 11, 12, 1, 3, 4, 7], '4': [3, 7, 6, 13, 1, 7, 11, 12, 1, 6, 11, 5, 2, 9, 12, 12, 1, 3, 6, 7], '13': [3, 4, 7, 6, 9, 11, 10, 1, 2]}
Last note, I have no clue whatsoever for why on Earth, you wanted the only keys left to be 6,4 and 13.
In any case, do not consider this as a full answer.
Now sure what you mean, so just created something that will cover most part. Change it with what you want.
dict_in = {'6': ['2,9,8,10'], '1': ['3,5,8,9,10,12'], '4': ['2,5,7,8,9'], '2': ['3,4,7,6,13'], '12': ['1,7,5,9'], '3': ['9,11,10,1,2,13'], '10': ['1,3,6,11'], '5': ['4,1,7,11,12'], '13': ['2,3'], '8' :['1,6,4,11'], '7': ['5,2,4,9,12'], '11': ['3,5,10,8'], '9': ['12,1,3,6,4,7']}
dict_out = {}
for key, values in dict_in.items():
for item in values:
if True:#your condition
if key in dict_out.keys():
dict_out[key].append(item)
else:
dict_out[key] = [item]
print(dict_out)
Related
This question already has answers here:
How do I sort a dictionary by key?
(32 answers)
Closed 2 years ago.
I have a dictionary that the keys representing the item and the value represent count of that.
for example in below dictionary:
dict= {'11': 4, '0': 2, '65': 1, '88': 1, '12': 1, '13': 1}
'11' occurred 4 times
'0' occurred 2 times
'65' occurred 1 time
How to order the dictionary that dict.keys() are descending or ascending?
The Ideal out put will be either
dict={'0':2,'11':4,'12':1,'13':1,'65':1,'88':1}
or
dict={'88':1,'65':1,'13':1,'12':1,'11':4,'0':2}
Any help would be appreciated
score = {'eng': 33, 'sci': 85, 'math': 60}
You can do it like this...
score_sorted = sorted(score.items(), key=lambda x:x[0])
If you wanna sort it by val, then score_sorted = sorted(score.items(), key=lambda x:x[1]). You can add reverse=True to change order as well.
Contrary to older posts dictionaries are no longer unordered and can be sorted since CPython 3.6 (unofficially, as a C implementation detail) and Python 3.7 (officially).
To sort by key use a dictionary comprehension to build a new dictionary in the order desired. If you want to sort by string collation order, use the following, but note that '2' comes after '11' as a string:
>>> d = {'11': 4, '2': 2, '65': 1, '88': 1, '12': 1, '13': 1}
>>> {k:d[k] for k in sorted(d)}
{'11': 4, '12': 1, '13': 1, '2': 2, '65': 1, '88': 1}
To order by integer value, pass a key function that converts the string to an integer:
>>> {k:d[k] for k in sorted(d,key=lambda x: int(x))}
{'2': 2, '11': 4, '12': 1, '13': 1, '65': 1, '88': 1}
Or reversed you can use reverse=True or just negate the integer:
>>> {k:d[k] for k in sorted(d,key=lambda x: -int(x))}
{'88': 1, '65': 1, '13': 1, '12': 1, '11': 4, '2': 2}
With older Python versions convert the dictionary to a list with list(d.items()) and use similar sorting.
myDict= {'11': 4, '0': 2, '65': 1, '88': 1, '12': 1, '13': 1}
sortDict = {}
for i in sorted(myDict.keys()) :
sortDict[i] = myDict[i]
print(sortDict)
dict= {'11': 4, '0': 2, '65': 1, '88': 1, '12': 1, '13': 1}
You can try dictionary comprehension like this
sorted_dict={k:dict[k] for k in sorted(dict)}
print(sorted_dict)
Note: Don't use dict as a variable name as it is already a built-in function.
your_dict = {'11': 4, '0': 2, '65': 1, '88': 1, '12': 1, '13': 1} is better.
You can use sample_list = list(your_dict.items()) which convets the given dict into a list.
In the Python Dictionary, items() method is used to return the list with all dictionary keys with values.
Use sample_list.sort() to sort the list.
To reverse the list, use reverse = True
sample_list = list(your_dict.items())
sample_list.sort(reverse = True)
Then use dict = dict(sample_list) to convert it into a dictionary and print it out.
I think the title is correct. If not, I apologize.
I have aList defined as
[24, 19, 18, 15, 15, 23, 18, 15, 18, 15]
and aDict defined as
{'1': 18, '2': 76, '3': 0, '4': 13, '5': 4, '6': 30, '7': 25, '8': 21}
and a masterDict defined (initialized with 0s) as
{'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}
How can I check whether each element in aList matches a value in aDict? If it does, increment the corresponding key in masterDict by 1?
The code i'm currently using is
for x in aList:
for k, v in aDict.iteritems():
if x == v:
masterDict[k] = +1
However, this is returning a masterDict that looks like this
{'1': 1, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}
aList contains three occurrences of the element 18 and it matches a value in aDict. I'm looking to increment the corresponding key in masterDict three times. However, it's only incrementing one time.
The output i'm looking to produce is
{'1': 3, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}
it is because of typo in your code - should be masterDict[k] += 1
instead of masterDict[k] = +1
after change output is: {'1': 3, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}
You can just use for k in dct and if the value that key produces matches item in lst then increase the k in mst by 1
mstr = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}
dct = {'1': 18, '2': 76, '3': 0, '4': 13, '5': 4, '6': 30, '7': 25, '8': 21}
lst = [24, 19, 18, 15, 15, 23, 18, 15, 18, 15]
for i in lst:
for k in dct:
if dct[k] == i:
mstr[k] += 1
print(mstr)
# {'1': 3, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}
def get_value(self):
"""Get the value on the face card:
(Jack=11, Queen=12, King = 13), Ace = 1, others are face value 2-10"""
#List that contains all the face cards that have a special value
specialJ = ['J']
specialK = ['K']
specialQ = ['Q']
#If the card is a jack, king, or queen, set the return value to 11,13,12
if self.rank in specialJ:
int_rank = '11'
elif self.rank in specialK:
int_rank = '13'
elif self.rank in specialQ:
int_rank = '12'
#If the card is an ace, set the return value to 1
elif self.rank == 'A':
#Set the return value of the card to 1
int_rank = '1'
#If the card is not a face card, keep the same return value.
else:
int_rank = self.rank
I am trying to assign the jack a value of 11, the queen a value of 12, the king a value of 13 by getting it to check if the card is found in the special lists. This does not work. I am not sure what I am doing wrong or how to do it.
You can use a list, like this
def get_value(self):
my_cards = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
return my_cards.index(self.rank) + 1
Even better, if you are going to access it often, dictionaries will give faster lookup
def get_value():
my_cards = {'A': 1, '10': 10, 'K': 13, 'J': 11, 'Q': 12, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
return my_cards.get(self.rank, -1)
def get_value():
my_cards = {'A': 1, '10': 10, 'K': 13, 'J': 11, 'Q': 12, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
return my_cards.get(self.rank, -1)
best way to do this
I have this dictionary:
d= {'1': { '2': 1, '3': 0, '4': 0, '5': 1, '6': 29 }
,'2': {'1': 13, '3': 1, '4': 0, '5': 21, '6': 0 }
,'3': {'1': 0, '2': 0, '4': 1, '5': 0, '6': 1 }
,'4': {'1': 1, '2': 17, '3': 1, '5': 2, '6': 0 }
,'5': {'1': 39, '2': 1, '3': 0, '4': 0, '6': 14 }
,'6': {'1': 0, '2': 0, '3': 43, '4': 1, '5': 0 }
}
I want to write a function that returns the column where all the values are <2 (less than 2).
So far i have turned the dictionary into a list, and then tried a lot of things that didn't work... I know that the answer is column number 4.
This was my latest attemp:
def findFirstRead(overlaps):
e= [[d[str(i)].get(str(j), '-') for j in range(1, 7)] for i in range(1, 7)]
nested_list = e
for i in map(itemgetter(x),nested_list):
if i<2:
return x+1
else:
continue
...and it was very wrong
The following set and list comprehension lists columns where the column has a max value of 2:
columns = {c for r, row in d.iteritems() for c in row}
[c for c in columns if max(v.get(c, -1) for v in d.itervalues()) < 2]
This returns ['4'].
This problem is teasing me:
I have 6 different sequences that each overlap, they are name 1-6.
I have made a function that represents the sequences in a dictionary, and a function that gives me the part of the sequences that overlap.
Now i should use those 2 functions to construct a dictionary that take the number of overlapping positions in both the right-to-left order and in the left-to-right oder.
The dictionary I have made look like:
{'1': 'GGCTCCCCACGGGGTACCCATAACTTGACAGTAGATCTCGTCCAGACCCCTAGC',
'2': 'CTTTACCCGGAAGAGCGGGACGCTGCCCTGCGCGATTCCAGGCTCCCCACGGG',
'3': 'GTCTTCAGTAGAAAATTGTTTTTTTCTTCCAAGAGGTCGGAGTCGTGAACACATCAGT',
'4': 'TGCGAGGGAAGTGAAGTATTTGACCCTTTACCCGGAAGAGCG',
'5': 'CGATTCCAGGCTCCCCACGGGGTACCCATAACTTGACAGTAGATCTC',
'6': 'TGACAGTAGATCTCGTCCAGACCCCTAGCTGGTACGTCTTCAGTAGAAAATTGTTTTTTTCTTCCAAGAGGTCGGAGT'}
I should end up with a result like:
{'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
'3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
'2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
'5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
'4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
'6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}
I seems impossible.
I guess it's not, so if somebody could (not do it) but push me in the right direction, it would be great.
This is a bit of a complicated one-liner, but it should work. Using find_overlaps() as the function that finds overlaps and seq_dict as the original dictionary of sequences:
overlaps = {seq:{other_seq:find_overlaps(seq_dict[seq],seq_dict[other_seq])
for other_seq in seq_dict if other_seq != seq} for seq in seq_dict}
Here it is with a bit nicer spacing:
overlaps = \
{seq:
{other_seq:
find_overlaps(seq_dict[seq],seq_dict[other_seq])
for other_seq in seq_dict if other_seq != seq}
for seq in seq_dict}
The clean way:
dna = {
'1': 'GGCTCCCCACGGGGTACCCATAACTTGACAGTAGATCTCGTCCAGACCCCTAGC',
'2': 'CTTTACCCGGAAGAGCGGGACGCTGCCCTGCGCGATTCCAGGCTCCCCACGGG',
'3': 'GTCTTCAGTAGAAAATTGTTTTTTTCTTCCAAGAGGTCGGAGTCGTGAACACATCAGT',
'4': 'TGCGAGGGAAGTGAAGTATTTGACCCTTTACCCGGAAGAGCG',
'5': 'CGATTCCAGGCTCCCCACGGGGTACCCATAACTTGACAGTAGATCTC',
'6': 'TGACAGTAGATCTCGTCCAGACCCCTAGCTGGTACGTCTTCAGTAGAAAATTG' \
'TTTTTTTCTTCCAAGAGGTCGGAGT'
}
def overlap(a, b):
l = min(len(a), len(b))
while True:
if a[-l:] == b[:l] or l == 0:
return l
l -= 1
def all_overlaps(d):
result = {}
for k1, v1 in d.items():
overlaps = {}
for k2, v2 in d.items():
if k1 == k2:
continue
overlaps[k2] = overlap(v1, v2)
result[k1] = overlaps
return result
print all_overlaps(dna)
(By the way, you could've provided overlap yourself in the question to make it easier for everyone to answer.)