如何将值从嵌套字典移动到另一个键?

发布于 2025-01-15 07:40:24 字数 621 浏览 2 评论 0原文

我怎样才能编写一个通过这个测试的函数? 如果匹配,该函数需要从reading_list中删除DATA,并添加到空读取列表中

my_data = {'read': [], 'reading_list': [{'c': 'H', 'd': 3.5, 'data': 'this book'}]}
DATA = 'this book'



#this is test case...

def test_moves_book_from_reading_list_to_empty_read():
    # Arrange
    my_data = {
        "reading_list": [{
            "title": DATA,
            "writer": WRITER,
            "rating": RATING_1
        }],
        "read": []
    }

    # Act
    updated_data = read_book(my_data, DATA)

    # Assert
    assert len(updated_data["reading_list"]) is 0
    assert len(updated_data["read"]) is 1

How I can write a function that pass this test?
this function need to remove DATA from reading_list if match, and add to empty read list

my_data = {'read': [], 'reading_list': [{'c': 'H', 'd': 3.5, 'data': 'this book'}]}
DATA = 'this book'



#this is test case...

def test_moves_book_from_reading_list_to_empty_read():
    # Arrange
    my_data = {
        "reading_list": [{
            "title": DATA,
            "writer": WRITER,
            "rating": RATING_1
        }],
        "read": []
    }

    # Act
    updated_data = read_book(my_data, DATA)

    # Assert
    assert len(updated_data["reading_list"]) is 0
    assert len(updated_data["read"]) is 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ヤ经典坏疍 2025-01-22 07:40:24

希望这有用。

>>> new_list = []
>>> my_data = {'read': [], 'reading_list': [{'c': 'H', 'd': 3.5, 'data': 'this book'}]}
>>> DATA = 'this book'
>>> if my_data.get('reading_list')[0].get('data') == DATA:
...     new_list.append(my_data.get('reading_list')[0].pop('data'))
... 
>>> my_data
{'read': [], 'reading_list': [{'c': 'H', 'd': 3.5}]}
>>> new_list
['this book']

Hope this is useful.

>>> new_list = []
>>> my_data = {'read': [], 'reading_list': [{'c': 'H', 'd': 3.5, 'data': 'this book'}]}
>>> DATA = 'this book'
>>> if my_data.get('reading_list')[0].get('data') == DATA:
...     new_list.append(my_data.get('reading_list')[0].pop('data'))
... 
>>> my_data
{'read': [], 'reading_list': [{'c': 'H', 'd': 3.5}]}
>>> new_list
['this book']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文