Reputation: 175
I have such a dictionary:
df = pd.read_csv(file, header=None)
l = (df.to_dict())
{0: {0: '1', 1: '6 4', 2: '2 4 8', 3: '4 6 7 2'}}
and I want to sort the values of each key in descending order which will be:
{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}
Upvotes: 2
Views: 229
Reputation: 1516
Here's a solution using several list/dictionary comprehensions:
d = {0: {0: '1', 1: '6 4', 2: '2 4 8', 3: '4 6 7 2'}} # original dictionary
# grab the inner dictionary to sort
inner_d = list(d.values())[0]
# reverse order as int
sorted_vals = [sorted(list(map(int, i.split())))[::-1] for i in inner_d.values()]
# convert back to list of joined strings
sorted_vals = [" ".join(a) for a in [[str(j) for j in i] for i in sorted_vals]]
# rebuild inner dictionary
inner_d = {k:v for k,v in zip(inner_d.keys(), sorted_vals)}
# put back into outer dictionary
d = {0:inner_d}
Result: {0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}
Upvotes: 0
Reputation: 27567
Here's a way:
a = {0: {0: '1', 1: '6 4', 2: '2 4 8', 3: '4 6 7 2'}}
for k in a[0].keys():
a[0].update({k:' '.join(sorted(a[0][k].split(),reverse=True))})
print(a)
Output:
{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}
Upvotes: 0
Reputation: 142
You can use one temporary dictionnary and two loops
for key, value in d.items():
tmp = {}
for key1, value1 in value.items():
tmp[key1] = ' '.join(sorted(value1.split(' '), reverse=True))
d[key] = tmp
output :
{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}
Upvotes: 1
Reputation: 13878
You can use a nested dict comprehension:
sep = ' '
result = {
row: {
k: sep.join(sorted(v.split(sep), reverse=True))
for k, v in val.items()
} for row, val in l.items()
}
Result:
{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}
As mentioned in my comment, if you only need to read a csv
as a dict
, pandas
is rather overkill. Look into the csv.DictReader
object as a viable alternative.
Upvotes: 2
Reputation: 1908
You can use dict comprehension for a one line solution, although it will become harder to read. You'll have to split the string into a list, sort it, and then join it back. You can try something like this:
dict = {0: {0: '1', 1: '6 4', 2: '2 4 8', 3: '4 6 7 2'}}
result = { 0 : { key : ' '.join(sorted(dict[0][key].split(),reverse=True)) for key in dict[0].keys() } }
Output:
>>> result
{0: {0: '1', 1: '6 4', 2: '8 4 2', 3: '7 6 4 2'}}
Note:
Upvotes: 0
Reputation: 793
You can use dict comprehension to create a new dict, with the values sorted.
df = pd.read_csv(file, header=None)
l = (df.to_dict())
{key:sorted(value) for key, value in l['0'].items()}
Since your data is not properly formated, you can turn space delimited strings of numbers into list using "split".
df = pd.read_csv(file, header=None)
l = (df.to_dict())
{key:sorted(value.split(' ')) for key, value in l['0'].items()}
If you need to sort the keys as well, you will need and ordered dict
Upvotes: 0