Dict Key и Value заполняются в результате разделения каждого элемента в списке python - PullRequest
0 голосов
/ 05 мая 2020

Я пытаюсь разбить этот список на два списка, а затем заполнить его в словаре для ключей и элементов.

У меня есть список заявлений для каждой отрасли, и я хотел бы разделить этот список на два списка . 1 с заявлениями и 1 с отраслями. В этом случае отрасль будет ключевой для словаря, значение которого будет выражением.

['“Significant shortages of personal protective equipment PPE, chemical reagents, test swabs and other basic medical supplies persist. Extreme sourcing measures are required to procure necessary supplies for basic operations. Distributor allocations continue across the board.” Health Care & Social Assistance', '“Severe impact to operations as a result of COVID-19. Major challenges in obtaining needed supplies for first responders, including N95 masks, gowns, disinfecting products and medical supplies. As a local government, we are experiencing a significant increase in activity due to emergency-response efforts. Starting to experience inappropriate price increases for short-supply items.” Public Administration', '“Significant demand disruption caused by the coronavirus.” Accommodation & Food Services', '“The coronavirus is having an impact, but not as much as we thought it would at this point. All sectors are staying busy. Although there are many customer concerns, we are finding work-arounds and adapting to the ever-changing situation.” Construction', '“COVID-19 shelter-in-place order in effect. Offices closed except for essential personnel.” Educational Services', '“Like most businesses, we cannot fully project how the coronavirus will impact us. By displaying prudence and avoiding panic, we are trying to navigate this crisis. As human capital is our greatest expense, protecting that capital is job one. Supply chains are overstressed and will normalize only when the panic subsides.” Information', '“COVID-19 has greatly impacted daily operations. All staff personnel are telecommuting, and customer concerns have shifted from normal activities to preventative measures.” Management of Companies & Support Services', '“We are experiencing no real issues from a business perspective, although COVID-19 has forced us to reconsider elements of how our workforce gets things done.” Mining', '“As expected for many industries whether manufacturing or non-manufacturing, purchasing has slowed as we evaluate the economic climate and prepare for long-term effects.” Retail Trade', '“The coronavirus is effecting every aspect of business.” Real Estate, Rental & Leasing']

Идеальным результатом было бы разделение двух списков как таковых:

New List 1 = [“Significant shortages of personal protective equipment PPE, chemical reagents, test swabs and other basic medical supplies persist. Extreme sourcing measures are required to procure necessary supplies for basic operations. Distributor allocations continue across the board.”, ....., “The coronavirus is effecting every aspect of business.”]

New List 2 = [Health Care & Social Assistance, ....., Real Estate, Rental & Leasing]

Список 2 будет ключом к словарю, а список 1 будет сохраненным значением.

dictionary = dict(zip(List2,List1))

Спасибо за вашу помощь.

Ответы [ 2 ]

0 голосов
/ 05 мая 2020
  1. Не New List 1 и New List 2, а list1 и list2.
    (Без пробелов и заглавных букв - см. PEP 8 - Имена функций и переменных .)

  2. Не

    New List 2 = [Health Care & Social Assistance, ....., Real Estate, Rental & Leasing]
    

    но

    list2 = ["Health Care & Social Assistance", ....., "Real Estate", "Rental & Leasing"]
    

    (строки в кавычках).

  3. Не dictionary = dict(zip(List2,List1)), а dictionary = dict(zip(list2, list1))
    (в соответствии с 1.).

0 голосов
/ 05 мая 2020

Вы можете разделить отчеты и отрасли, выполнив поиск по index. Если ваш исходный список называется L:

industries = [s[s.index("”")+2:] for s in L]
statements = [s[1:s.index("”")] for s in L]
dictionary = dict(zip(industries, statements))

Но вы также можете создать свой dict напрямую с пониманием dict:

dictionary = {e[e.index("”")+2:]: e[1:e.index("”")] for e in L}
...