0

I have several dictionaries( Class1 , Class2) , and one element of the dictionary stores a list (Score) , I want to put the element of the list into another list , but not the list itself to another list .

I try the following code

All = []
Class1 = {"name":"A","score":[60,70,80]}
Class2 = {"naem":"B","score":[70,80,90]}
All.append(Class1['score'])
All.append(Class2['score'])
print(All)

but the result is

[[60, 70, 80], [70, 80, 90]]

but what I want is

[60, 70, 80, 70, 80, 90]

I try this solution below , but I want to know does there exists better solution?

All = []
Class1 = {"name":"A","score":[60,70,80]}
Class2 = {"naem":"B","score":[70,80,90]}

Scores1 = Class1['score']
Scores2 = Class2['score']

Scores = Scores1 + Scores2
for score in Scores:
    All.append(score)

print(All)

thanks

user2131116
  • 2,761
  • 6
  • 26
  • 33
  • 2
    What exactly does *better* mean for you in this context? – sloth Jul 15 '13 at 12:58
  • a better solution means a shorter solution .... – user2131116 Jul 15 '13 at 13:07
  • funny the number of thing so well hidden in the documentation (such as `extend`) – njzk2 Jul 15 '13 at 13:10
  • in your example, just remove the temp variable Score. `All = Scores1 + Scores2` works just as you want it to. – njzk2 Jul 15 '13 at 13:11
  • Why += is slightly better than extend() is discussed [here](http://stackoverflow.com/questions/3653298/concatenating-two-lists-difference-between-and-extend) – Sudipta Jul 15 '13 at 13:15
  • Let me explain some things I store many class dictionaries into a list (Dataset) and I want to put into All list so `for element in Dataset: All.extend(element['score'])` will be best choice of my answer ...... – user2131116 Jul 15 '13 at 13:21
  • 2
    You can also do: `for element in Dataset: All += element['score']`. It's completely your choice though :) – Sudipta Jul 15 '13 at 13:23

5 Answers5

6

You can use extend:

extend(...)

L.extend(iterable) -- extend list by appending elements from the iterable
All = []
Class1 = {"name":"A","score":[60,70,80]}
Class2 = {"naem":"B","score":[70,80,90]}
All.extend(Class1['score'])
All.extend(Class2['score'])
print(All)
Community
  • 1
  • 1
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
3

All.extend(...) will do what you want...

Roger
  • 151
  • 7
3
All = Class1["score"] + Class2["score"]

To add more elements later:

ALL += Classx["score"]
Sudipta
  • 4,773
  • 2
  • 27
  • 42
3

When you call All.append(Class1['score']), the list contained in your dictionnary is treated as a single element and added to your All list as a whole.

You either have to loop through each item in the list, as you did, or use the list.extend method, which will merge your list with another iterator, ie append every item from that other iterator to your starting list.

astrognocci
  • 1,057
  • 7
  • 16
3

If All might already contain elements:

All.extend(Class1["score"] + Class2["score"])
Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75