I'm currently working on a small project (I'm relatively new to python) in which I have a dictionary of items (as an example):
dic = {
'ab': 'a',
'ac': 'a',
'bc': 'b',
'bd': 'b',
'cd': 'c',
'ce': 'c'
}
And would like to convert it into a list with each initial index being correlated to one of the values
sorted_lst[0][1] = ab
sorted_lst[2][1] = ce
and so forth. How would I go about doing this? Would it be easier to start with a sorted list rather than a dictionary?
The reason for doing so, is that I would like to print out columnal lists of guesses in which their assignment is derived from the initial letter of the guess. ie. something like:
ab bc cd
ac bd ce
So that the user can see their guesses in a more appealing way rather than just as an alphabetized list.
CodePudding user response:
Looks like you could use a defaultdict
to transform your data to 2D:
from collections import defaultdict
d = defaultdict(list)
for k,v in dic.items():
d[v].append(k)
sorted_lst = list(d.values())
# or to ensure sorting of the first level:
# sorted_lst = [d[k] for k in sorted(d)]
sorted_lst[0][1]
# ac
sorted_lst[2][1]
# ce
output: [['ab', 'ac'], ['bc', 'bd'], ['cd', 'ce']]
CodePudding user response:
Here is one way to do so:
- We sort the unique values, then loop through each one and group the keys into a list.
data = {
'ab': 'a',
'ac': 'a',
'bc': 'b',
'bd': 'b',
'cd': 'c',
'ce': 'c'
}
sorted_data = []
for item in sorted(set(data.values())):
sorted_data.append([key for key in data.keys() if data[key] == item])
# sorted_data = [['ab', 'ac'], ['bc', 'bd'], ['cd', 'ce']]
You can also use setdefault()
:
sorted_data = {}
for key, item in data.items():
sorted_data.setdefault(item, []).append(key)
sorted_data = list(sorted_data.values())
To print the values you can then loop over each item:
for i in range(len(sorted_data[0])):
for j in range(len(sorted_data)):
print(sorted_data[j][i], end=" ")
print("")
output:
ab bc cd
ac bd ce