简体   繁体   中英

How to sort values of a dictionary based on the criteria imposed by values of a list in a new dictionary?

Apologies for the title, couldn't figure out a way to phrase this, if anyone has suggestions I'm happy to edit!

Basically, I have a dictionary and a list. The dictionary:

dict1 = {('red fruit', 'green fruit'): 'apple', ('orange fruit', 'pink fruit'): 'peach', ('five fruit', 'one fruit'): 51, ('ten fruit', 'nine fruit'): 19, ('period', 'exclamation mark'): '.!'}

The list:

list1 = [('alphabet'), ('number'), ('neither')]

What I'm trying to do is to sort the values of the dictionary keys based on the items in the list and return a new dictionary, where the values are now the keys of dict1 and the new keys are the items in the list.

The values for ('alphabet') should be the keys of dict1 when their values are alphabetical, The values for ('number') should be the keys of dict1 when their values are numerical, and the values of ('neither') should be when the values of the keys fail both cases.

For example, my output should be:

{('alphabet'): [('red fruit', 'green fruit'), ('orange fruit', 'pink fruit')], ('number'): [('five fruit', 'one fruit'), ('ten fruit', 'nine fruit')], ('neither'): [('period', 'exclamation mark')]}

I started off by creating a new dictionary with the keys from the list and the values as empty lists, and I want to add values when they fit the requirements stated above (probably by using.isdigit() and.isalpha()) into the empty lists. But I don't really understand how to add the values to the specific keys when they pass the requirements?

I'm a beginner so simple, short codes without importing modules or list comprehension would be ideal, but any guidance will be much appreciated! Thanks!

You can loop over key, value pairs in the dictionary, appending keys to the appropriate list, and use these to form a new dictionary.

dict1 = {('red fruit', 'green fruit'): 'apple',
         ('orange fruit', 'pink fruit'): 'peach',
         ('five fruit', 'one fruit'): 51,
         ('ten fruit', 'nine fruit'): 19,
         ('period', 'exclamation mark'): '.!'}

list1 = [('alphabet'), ('number'), ('neither')]

alphabetical = []
numerical = []
other = []

for key, value in dict1.items():

    if isinstance(value, int):
        numerical.append(key)

    elif value.isalpha():
        alphabetical.append(key)

    else:
        other.append(key)

list2 = {'alphabet': alphabetical,
         'number': numerical,
         'neither': other}

print(list2)

Note that where you are using eg ('foo') this is the same as 'foo' (although above I have kept the syntax that you were using when assigning list1 ).

Here I have used isinstance(..., int) because your data items are integers. isdigit would only be relevant if they were strings containing digits.

Also note that isalpha will only evaluate True if all the characters in the string are alphabetical. The method is primarily intended for use with single characters, but the question does not specify what should happen if the string contains a mixture of types of character, so I have kept it here. But if for example you had a space in the middle of one of your dictionary values, then isalpha would return False even if the remaining characters were alphabetical.

If I'm understanding correctly, you want to filter out dictionary keys based on the type of their values and then order the keys by their types as stated in a separate list.

To determine the type of strings, you need to be more exact about what counts as 'alphabet' instead of just listing the name of the things you want to define. For example:

def string_type(s):
    if s.isalpha():
        return 'alphabet'
    elif s.isdigit():
        return 'number'
    else:
        return 'neither'

Then, you can proceed to filter out the keys you want and put them into a dictionary by the order you specified in list1

def process(dict1, list1):
    output = {k: [] for k in list1}
    for key, val in dict1.items():
        t = string_type( str(val) )
        if t in list1:
            output[t].append(key)
    return output

Example outputs:

>>> dict1 = {('red fruit', 'green fruit'): 'apple', ('orange fruit', 'pink fruit'): 'peach', ('five fruit', 'one fruit'): 51, ('ten fruit', 'nine fruit'): 19, ('period', 'exclamation mark'): '.!'}

>>> list1 = [('alphabet'), ('number'), ('neither')]
>>> process(dict1, list1)
{'alphabet': [('red fruit', 'green fruit'), ('orange fruit', 'pink fruit')], 'number': [('five fruit', 'one fruit'), ('ten fruit', 'nine fruit')], 'neither': [('period', 'exclamation mark')]}

>>> list2 = [('number'), ('neither'), ('alphabet')]
>>> process(dict1, list2)
{'number': [('five fruit', 'one fruit'), ('ten fruit', 'nine fruit')], 'neither': [('period', 'exclamation mark')], 'alphabet': [('red fruit', 'green fruit'), ('orange fruit', 'pink fruit')]}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM