如何对字典排序并按字母顺序设置?

时间:2020-08-06 12:43:48

标签: python python-3.x list dictionary set

我已经创建了这段代码,以显示人们在读书俱乐部还没有读过哪些书。

我写的代码是

Books = {}
Names = []
temp1 = set()
line = input('Book read: ')
while line:
  Book, Name = line.split(':')
  if Book not in Books:
    # add it to our dictionary as a list with one element
    Books[Book] = [Name]
  else:
    Books[Book].append(Name)
  line = input('Book read: ')
  
  if Name not in Names :
    Names.append(Name)
    
Names = list(dict.fromkeys(Names))

for Name in Names:
  temp1.add(Name)
  
BookSorted = dict(sorted(Books.items()))

for Book in BookSorted:
  if BookSorted[Book] == Names :
    print(Book + ": Everyone has read this!")
  else:
    temp2 = set(BookSorted[Book])
    print(Book, ':', ', '.join(temp1 - temp2))

这确实有用,但是书籍列表和名称都没有按字母顺序排列。 (我已删除了各种尝试,以便您可以更轻松地阅读。)

当提供以下测试样品时

Book read: Pride and Prejudice:Jenny
Book read: A Tale of Two Cities:Mark
Book read: Magician:Jenny
Book read: The Lord of the Rings:Pavel
Book read: Magician:Pavel

我的代码返回

Pride and Prejudice: Mark, Pavel
A Tale of Two Cities: Pavel, Jenny
Magician: Mark
The Lord of the Rings: Mark, Jenny

何时返回

A Tale of Two Cities: Jenny, Pavel
Magician: Mark
Pride and Prejudice: Mark, Pavel
The Lord of the Rings: Jenny, Mark

任何帮助将不胜感激:)

最亲切的问候

2 个答案:

答案 0 :(得分:0)

使用书名作为键,将读者作为值来指定字典,您可以执行以下操作:

data = {
    "Pride and Prejudice": ["Mark", "Pavel"],
    "A Tale of Two Cities": ["Pavel", "Jenny"],
    "Magician": ["Mark"],
    "The Lord of the Rings": ["Mark", "Jenny"]
}

data = dict(sorted(data.items()))


# just a short print loop to show you the order

for k,v in data.items():
    print(k+":"+str(v))

#A Tale of Two Cities:['Pavel', 'Jenny']
#Magician:['Mark']
#Pride and Prejudice:['Mark', 'Pavel']
#The Lord of the Rings:['Mark', 'Jenny']

答案 1 :(得分:0)

注释和其他解决方案对排序和字典进行了很好的讨论。恕我直言,认为/假定字典或集合已排序是很危险的,因为按设计,它们不是要订购的。有了其他想法的警告后,您可以执行此操作,或切换到OrderedDict,这会带来一些开销。我的建议是仅在需要时“对键进行排序”。当然,如果您发现需要执行很多操作,那么这就是切换到不同数据结构的动力。

这是一个切入点,还有一些其他增强功能:

  • 在进行交集/差之类的集合式操作时,请使用set。干净得多
  • 不要将大写字母用作变量名... python标准是小写字母
  • 您几乎可以肯定要strip()从条目中引出/尾随空格,这样您就不会迷恋以下两者之间的区别:

Cat in Hat: Bob
Cat in Hat:Bob

# sorting books

books = {}          # title : set of readers
all_names = set()   # all reader names set
line = input('Enter book title : name ')
while line:
  book, name = [t.strip() for t in line.split(':')]   # strip out pesky leading/trailing spaces.
  if book not in books:
    # add it to our dictionary as a list with one element
    books[book] = {name, }  # a set with one item
  else:
    books[book].add(name)
  
  all_names.add(name)       # set will not accept duplicates, so this works...
    
  line = input('Enter book title : name ')

# now we have a dictionary of book : set of names that have read it
# and a set of all names that we can use

for k in sorted(books):  # sort the keys only when needed
  non_readers = all_names ^ books[k]
  # note: ^ is symmetric difference, so result will be names in all_names that are not in readers
  if non_readers:  # non-empty response
    print(f'{k} has not been read by: {", ".join(sorted(non_readers))}')
  else:
    print(f'Everyone has read {k}')

在修改了这些内容之后,我意识到您可能没有经营读书俱乐部,而且这很可能是一项硬件任务,所以现在我对此感到难过...大声笑。

相关问题