Как нарезать словарь в python и Robot-framework? - PullRequest
0 голосов
/ 08 декабря 2018

Нарезка доступна для списков в python

list1 =[1,2,3,4,5,6]
list1[:3]
[1, 2, 3]

Аналогично, нарезка или что-то похожее на то, что доступно для словаря?

dict1 = {1":a",2:"b",3:"c",4:"d",5:"e"} 

Я хотел бы получить любые 3 (может бытьслучайные) элементы словаря, просто предоставив номер (как указано выше для списка [:2]), тогда я должен получить значение ниже словаря

dict1 = {1":a",2:"b"} # After slicing

Как может быть достигнут этот срез словаря или альтернатива в python& Robot-framework?

Ответы [ 3 ]

0 голосов
/ 09 декабря 2018

Просто чтобы предоставить 2 альтернативы, используя только ключевые слова Robot Framework.По сути, они придерживаются аналогичного подхода.Получите ключи из словаря, затем нарежьте их и измените или заново создайте словарь в нужном формате.

Если нет особых причин не использовать Python для этого, я думаю, что эта функциональность должна быть обеспеченапо ключевому слову Python, а не по Robot Framework.

*** Settings ***
Library    Collections

*** Variables ***
&{dict1}    1=a    2=b    3=c    4=d    5=e
&{dict2}    1=a    2=b    3=c    4=d    5=e
&{result}   3=c    4=d    5=e 

*** Test Cases ***
TC - keep items 3, 4 & 5
    # Keey
    Keep Slice In Dictionary    ${dict1}    ${5}    ${2}
    Log Many    ${dict1}
    Dictionaries Should Be Equal    ${dict1}    ${result}    

    ${slice}       Get Slice From Dictionary    ${dict2}    ${5}    ${2}
    Log Many    ${slice}
    Dictionaries Should Be Equal    ${dict1}    ${slice}

*** Keywords ***
Keep Slice In Dictionary
    [Documentation]
    ...    Modifies the dictionary to only leave the slice.
    ...    
    ...    The keys of the dictionary are converted into a list. Then
    ...    this list is spliced. This list is then used to filter out
    ...    the unwanted keys.
    ...    
    ...    Note: this keyword modifies the provided dictionary.
    ...    
    ...    Arguments:
    ...    - dict    (dictionary)    The dictionary that needs to be modified
    ...    - high    (integer)       The last item to be kept.
    ...    - low     (integer)       The first item of the slice. (defaults to 0)
    ...    
    ...    Returns:    None          Modifies the provided dictionary.
    ...    
    [Arguments]    ${dict}    ${high}    ${low}=${0}

    ${keys_list}        Get Dictionary Keys    ${dict}
    ${filtered_keys}    Get Slice From List    ${keys_list}    ${low}    ${high}
    Keep In Dictionary     ${dict}    @{filtered_keys}

Get Slice From Dictionary
    [Documentation]
    ...    Get a slice of sequential keys from a dictionary
    ...    
    ...    The keys of the dictionary are converted into a list. Then
    ...    this list is spliced. This list is then used to create a new
    ...    Dictionary with the filtered keys.
    ...    
    ...    Arguments:
    ...    - dict    (dictionary)    The source dictionary
    ...    - high    (integer)       The last item to be kept.
    ...    - low     (integer)       The first item of the slice. (defaults to 0)
    ...    
    ...    Returns:  (dictionary     A dictionary with the desired keys.
    ...    
    [Arguments]    ${dict}    ${high}    ${low}=${0}
    ${keys_list}        Get Dictionary Keys    ${dict}
    ${filtered_keys}    Get Slice From List    ${keys_list}    ${low}    ${high}

    ${return_dict}    Create Dictionary

    :FOR    ${item}    IN    @{filtered_keys}
    \        Set To Dictionary    ${return_dict}   ${item}    ${dict['${item}']}

    [Return]     ${return_dict}
0 голосов
/ 10 декабря 2018

Я хотел бы получить любые 3 (могут быть случайными) элементы словаря

Построение списка всех элементов словаря не требуется.Вы можете использовать dict.items и itertools.islice, чтобы нарезать фиксированное количество элементов:

from itertools import islice

def get_n_items(d, n):
    return dict(islice(d.items(), 0, n))

dict1 = {1:"a", 2:"b", 3:"c", 4:"d", 5:"e"} 

get_n_items(dict1, 2)  # {1: 'a', 2: 'b'}
get_n_items(dict1, 3)  # {1: 'a', 2: 'b', 3: 'c'}

С Python 3.6+, как подробности реализации вCPython 3.6 и официально в 3.7+, это равносильно получению первых n предметов в порядке орошения.

0 голосов
/ 08 декабря 2018

Может быть, это решение, которое вы могли бы рассмотреть, поскольку к dict нельзя получить доступ как list:

dict1 = {1:"a",2:"b",3:"c",4:"d",5:"e"}

def take(dct, high=None, low=None):
  return dict(list(dct.items())[low:high])

print(take(dict1, 3)) #=> {1: 'a', 2: 'b', 3: 'c'}
print(take(dict1, 5, 2)) #=> {3: 'c', 4: 'd', 5: 'e'}
...