0

I'm just starting out at Python and need some help with dictionaries. I'm looking to add keys to a dictionary based on input that is a list with string elements:

Ex.

x = {}
a = ['1', 'line', '56_09', '..xxx..']

Now say a while loop has come to this list a. I try to add to the dictionary with this code:

if a[1] == 'line':
    x[a[2]] = [a[-1]]

I want the dictionary to read x = { '56_09': '..xxx..'} and want to confirm that by printing it. Do i need to adjust the elements on the list to strings or is it something with the if statement that I need to change?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Jrills
  • 1

4 Answers4

2

The one problem with your code is in the if block:

if a[1] == 'line':
    x[a[2]] = [a[-1]]

Instead, it should be like this:

if a[1] == 'line':
    x[a[2]] = a[-1]

What you did was creating a list with one element: the last element of the list a.

Tim Zimmermann
  • 6,132
  • 3
  • 30
  • 36
0

you can make a dict object form two lists using ZIP and dict()

dict(zip(list1,list2)).

I believe for your question make two list form the input list based on the requirement and use above syntax.

rsirs
  • 107
  • 7
0

I think you need something like this : -

def check(x,a):
    if 'line' in a[1]:
        x[a[2]] = a[-1]
        return x

After

check({},['1', 'line', '56_09', '..xxx..'])
Shekhar Samanta
  • 875
  • 2
  • 12
  • 25
0
if a[1]=='line':
    x={a[2]:a[-1]}

dictionary comprehension Create a dictionary with list comprehension in Python

{r:"test" for r in range(10)}
Community
  • 1
  • 1
python必须死
  • 999
  • 10
  • 12