如何根据新字典中列表的值所强加的标准对字典的值进行排序



为这个标题道歉,想不出一种表达方式,如果有人有建议,我很乐意编辑!

基本上,我有一本字典和一份清单。字典:

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')]

我试图做的是根据列表中的项目对字典键的值进行排序,并返回一个新字典,其中的值现在是dict1的键,新键是列表中的项。

当("alphabet"(的值按字母顺序排列时,它们应该是dict1的键。当("number"(的数值为数字时,它们的值应该是dict 1的键,当键的值在这两种情况下都失败时,("nore"(应该是。

例如,我的输出应该是:

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

我首先创建了一个新的字典,其中包含列表中的键和空列表中的值,当它们符合上述要求时,我想将值添加到空列表中(可能通过使用.idigit((和.isalpha(((。但我真的不明白当特定的键通过要求时,如何将值添加到它们中?

我是一个初学者,所以简单,没有导入模块或列表理解的短代码是理想的,但任何指导都将不胜感激!谢谢

如果我理解正确,您需要根据字典键的值的类型筛选出它们,然后按照单独列表中的类型对键进行排序。

要确定字符串的类型,您需要更准确地了解什么是"字母表",而不仅仅是列出要定义的东西的名称。例如:

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

然后,您可以继续过滤出您想要的密钥,并按照您在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

示例输出:

>>> 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')]}

您可以循环遍历字典中的键和值对,将键附加到适当的列表中,并使用它们来形成一个新的字典。

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)

请注意,在使用例如('foo')的情况下,这与'foo'相同(尽管上面我保留了分配list1时使用的语法(。

这里我使用了isinstance(..., int),因为您的数据项是整数。只有当它们是包含数字的字符串时,isdigit才是相关的。

还要注意,如果字符串中的所有字符都是按字母顺序排列的,则isalpha将仅计算True。该方法主要用于单个字符,但问题没有指定如果字符串包含多种类型的字符,会发生什么,所以我将其保留在这里。但是,例如,如果您的一个字典值中间有一个空格,那么即使剩余的字符是按字母顺序排列的,isalpha也会返回False

最新更新