-1

i am trying to find a way to print out a new list from an existing dictionary in python. I want to be able create a new list with each of the fabric types based off of the entries in the dictionary, instead of printing out the entire dictionary. I am still a beginner trying to figure it out. All other ways resulted in errors. Here is the code i have so far, but i feel there has to be an easier way than repeatedly breaking the loop for the same task. Any suggestions?

Clothes_in_Closet = [{
                "type" : "sweater",
                "fabric" : "wool", 
                "size" : "s", 
                
            }, 
            {    
                "type" : "shirt",
                "fabric" : "cotton", 
                "size" : "m", 
            },
            {
                "type" : "jeans",
                "fabric" : "cotton blend",
                "size" : "m", 
            }
                ]
newList = [ ]          

for fabrics in Clothes_in_Closet:
  fabrics = Clothes_in_Closet [0]["fabric"]
  newList.append(fabrics)
  break
for fabrics in Clothes_in_Closet:
  fabrics = Clothes_in_Closet [1]["fabric"]
  newList.append(fabrics)
  break
for fabrics in Clothes_in_Closet:
  fabrics = Clothes_in_Closet [2]["fabric"]
  newList.append(fabrics)
  break
print(newList)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

1 Answers1

1

Use list comprehension and grab the value associated with key fabric:

newList = [cloth['fabric'] for cloth in Clothes_in_Closet]
print(newList)

Output:

['wool', 'cotton', 'cotton blend']

You can use the traditional looping approach as well instead of list comprehension but note that list comprehension is preferred over traditional looping in Python:

newList = []
for cloth in Clothes_in_Closet:
    newList.append(cloth['fabric'])
    
print(newList)
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35