473,569 Members | 2,729 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return dictionary values as single list

50 New Member
Can anyone suggest a better way of returning the values in a dictionary as a single list. I have the following, but it uses a nested loop, not sure if there is a more efficient way.

Expand|Select|Wrap|Line Numbers
  1. >>> d['a']= [(45,6)]
  2. >>> d['a'].append((56,4))
  3. >>> d['a']
  4. [(45, 6), (56, 4)]
  5. >>> s =[]
  6. >>> for i, j in enumerate(d['a']):
  7. ...     for k, l in enumerate(j):
  8. ...         s.append(l)
  9. ...         
  10. >>> s
  11. [45, 6, 56, 4]
  12. >>> 
  13.  
thanks
Aug 15 '07 #1
6 1834
ilikepython
844 Recognized Expert Contributor
Can anyone suggest a better way of returning the values in a dictionary as a single list. I have the following, but it uses a nested loop, not sure if there is a more efficient way.

Expand|Select|Wrap|Line Numbers
  1. >>> d['a']= [(45,6)]
  2. >>> d['a'].append((56,4))
  3. >>> d['a']
  4. [(45, 6), (56, 4)]
  5. >>> s =[]
  6. >>> for i, j in enumerate(d['a']):
  7. ...     for k, l in enumerate(j):
  8. ...         s.append(l)
  9. ...         
  10. >>> s
  11. [45, 6, 56, 4]
  12. >>> 
  13.  
thanks
Expand|Select|Wrap|Line Numbers
  1. s = [value for tup in d['a'] for value in tup]
  2.  
Hope that helps.
Aug 15 '07 #2
bartonc
6,596 Recognized Expert Expert
Can anyone suggest a better way of returning the values in a dictionary as a single list. I have the following, but it uses a nested loop, not sure if there is a more efficient way.

Expand|Select|Wrap|Line Numbers
  1. >>> d['a']= [(45,6)]
  2. >>> d['a'].append((56,4))
  3. >>> d['a']
  4. [(45, 6), (56, 4)]
  5. >>> s =[]
  6. >>> for i, j in enumerate(d['a']):
  7. ...     for k, l in enumerate(j):
  8. ...         s.append(l)
  9. ...         
  10. >>> s
  11. [45, 6, 56, 4]
  12. >>> 
  13.  
thanks
Expand|Select|Wrap|Line Numbers
  1. >>> aList = [(45, 6), (56, 4)]
  2. >>> newList = []
  3. >>> for tup in aList:
  4. ...     newList.extend(tup)
  5. ...     
  6. >>> newList
  7. [45, 6, 56, 4]
  8. >>> 
Aug 15 '07 #3
kdt
50 New Member
Sweet, thanks. Much better!
Aug 15 '07 #4
bartonc
6,596 Recognized Expert Expert
Sweet, thanks. Much better!
You did see mine, right? One minute apart, maybe you were posting while I was.
Aug 15 '07 #5
ilikepython
844 Recognized Expert Contributor
Expand|Select|Wrap|Line Numbers
  1. >>> aList = [(45, 6), (56, 4)]
  2. >>> newList = []
  3. >>> for tup in aList:
  4. ...     newList.extend(tup)
  5. ...     
  6. >>> newList
  7. [45, 6, 56, 4]
  8. >>> 
Just for fun, you could do that with map:
Expand|Select|Wrap|Line Numbers
  1. >>> aList = [(45, 6), (56, 4)]
  2. >>> newList = []
  3. >>> map(newList.extend, aList)
  4. >>> newList
  5. [45, 6, 56, 4]
  6.  
Aug 15 '07 #6
bartonc
6,596 Recognized Expert Expert
Just for fun, you could do that with map:
Expand|Select|Wrap|Line Numbers
  1. >>> aList = [(45, 6), (56, 4)]
  2. >>> newList = []
  3. >>> map(newList.extend, aList)
  4. >>> newList
  5. [45, 6, 56, 4]
  6.  
Bonus points to you, my friend! Two lines in one; very nicely done.
Aug 15 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

47
3596
by: Martin DeMello | last post by:
It seems to be a fairly common pattern for an object-modifying method to return None - however, this is often quite inconvenient. For instance def f(lst1, lst2): g((lst1 + lst2).reverse()) # doesn't work! you need to say
125
7115
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
90
10738
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in future Python versions and let dict.keys() and dict.values() both return sets instead of lists. If d is a dict, code like: for x in d.keys():
14
3444
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a list? I know that sets were introduced a lot later and lists/dictionaries were used instead but I think "the only correct way" now is for the...
4
34147
by: O.B. | last post by:
I need the ability to parse through the values of a Dictionary and remove certain ones depending on their attribute values. In the example below, an InvalidOperationException is thrown in the foreach statement when the first item is removed from the Dictionary. From looking at Dictionary's methods, I couldn't find anything to create a copy...
7
57529
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any way to convert from a dictionary to a list without itterating through the entire collection and building up a list? 2. is there a common base class, collection or interface that can contain...
4
9797
by: =?utf-8?B?TWFjaWVqIEJsaXppxYRza2k=?= | last post by:
Hi Pythonistas! I've got a question about storing tuples in a dictionary. First, a small test case which creates a list of dictionaries: import time list_of_dicts = keys = prev_clk = time.clock()
2
5869
by: Assimalyst | last post by:
Hi I have a Dictionary<string, List<string>>, which i have successfully filled. My problem is I need to create a filter expression using all possible permutations of its contents. i.e. the dictionary essentially creates the following array: Key Value
14
3802
by: lee | last post by:
hi, i have a dictionary as follows : kev : {'phno': , 'email': , 'name': , 'address': } if user is enters the 3rd item of key phno, ie "dfsdf" in my dict, how can i find it is the third item in the internal list of phno of that dictionary? thanks you.
0
7609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7666
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6278
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.