Remove items from dictionary if the length of the item is 1 or less












3















Quick question: Is there a way for me to remove a key from a dictionary using it's index position (if it has one) instead of using the actual key (to avoid e.g. del d['key'] but use index position instead)?



If there is then don't bother reading the rest of this question as that's what I'm looking for too.





So, as an example for my case, I have the dictionary d which uses lists for the values:



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}


I want to remove each key completely from such dictionary whose value's items have a length of less than 2 (so if there's only 1 item).



So, in this example I would want to remove the key 'acd' because it's value's list only has 1 item ['cad']. 'abd' has 2 items ['bad', 'dab'], so I don't want to delete it - only if it contains 1 or less item. This dictionary is just an example - I am working with a much bigger version than this and I need it to remove all of the single item value keys.



I wrote this for testing but I'm not sure how to go about removing the keys I want - or determing what they are.



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

index_pos = 0

for i in d.values():

#Testing and seeing stuff
print("pos:", index_pos)
print(i)
print(len(i))

if len(i) < 2:

del d[???]
#What do I do?

index_pos += 1


I used index_pos because I thought it might be useful but I'm not sure.



I know I can delete an entry from the dictionary using



del d['key']


But how do I avoid using the key and e.g. use the index position instead, or how do I find out what the key is, so I can delete it?



Hopefully I didn't make this too confusing.



Thanks










share|improve this question




















  • 1





    You could iterate over d.items() so you'll have key-value pairs.

    – Filip Młynarski
    Nov 24 '18 at 23:15
















3















Quick question: Is there a way for me to remove a key from a dictionary using it's index position (if it has one) instead of using the actual key (to avoid e.g. del d['key'] but use index position instead)?



If there is then don't bother reading the rest of this question as that's what I'm looking for too.





So, as an example for my case, I have the dictionary d which uses lists for the values:



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}


I want to remove each key completely from such dictionary whose value's items have a length of less than 2 (so if there's only 1 item).



So, in this example I would want to remove the key 'acd' because it's value's list only has 1 item ['cad']. 'abd' has 2 items ['bad', 'dab'], so I don't want to delete it - only if it contains 1 or less item. This dictionary is just an example - I am working with a much bigger version than this and I need it to remove all of the single item value keys.



I wrote this for testing but I'm not sure how to go about removing the keys I want - or determing what they are.



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

index_pos = 0

for i in d.values():

#Testing and seeing stuff
print("pos:", index_pos)
print(i)
print(len(i))

if len(i) < 2:

del d[???]
#What do I do?

index_pos += 1


I used index_pos because I thought it might be useful but I'm not sure.



I know I can delete an entry from the dictionary using



del d['key']


But how do I avoid using the key and e.g. use the index position instead, or how do I find out what the key is, so I can delete it?



Hopefully I didn't make this too confusing.



Thanks










share|improve this question




















  • 1





    You could iterate over d.items() so you'll have key-value pairs.

    – Filip Młynarski
    Nov 24 '18 at 23:15














3












3








3








Quick question: Is there a way for me to remove a key from a dictionary using it's index position (if it has one) instead of using the actual key (to avoid e.g. del d['key'] but use index position instead)?



If there is then don't bother reading the rest of this question as that's what I'm looking for too.





So, as an example for my case, I have the dictionary d which uses lists for the values:



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}


I want to remove each key completely from such dictionary whose value's items have a length of less than 2 (so if there's only 1 item).



So, in this example I would want to remove the key 'acd' because it's value's list only has 1 item ['cad']. 'abd' has 2 items ['bad', 'dab'], so I don't want to delete it - only if it contains 1 or less item. This dictionary is just an example - I am working with a much bigger version than this and I need it to remove all of the single item value keys.



I wrote this for testing but I'm not sure how to go about removing the keys I want - or determing what they are.



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

index_pos = 0

for i in d.values():

#Testing and seeing stuff
print("pos:", index_pos)
print(i)
print(len(i))

if len(i) < 2:

del d[???]
#What do I do?

index_pos += 1


I used index_pos because I thought it might be useful but I'm not sure.



I know I can delete an entry from the dictionary using



del d['key']


But how do I avoid using the key and e.g. use the index position instead, or how do I find out what the key is, so I can delete it?



Hopefully I didn't make this too confusing.



Thanks










share|improve this question
















Quick question: Is there a way for me to remove a key from a dictionary using it's index position (if it has one) instead of using the actual key (to avoid e.g. del d['key'] but use index position instead)?



If there is then don't bother reading the rest of this question as that's what I'm looking for too.





So, as an example for my case, I have the dictionary d which uses lists for the values:



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}


I want to remove each key completely from such dictionary whose value's items have a length of less than 2 (so if there's only 1 item).



So, in this example I would want to remove the key 'acd' because it's value's list only has 1 item ['cad']. 'abd' has 2 items ['bad', 'dab'], so I don't want to delete it - only if it contains 1 or less item. This dictionary is just an example - I am working with a much bigger version than this and I need it to remove all of the single item value keys.



I wrote this for testing but I'm not sure how to go about removing the keys I want - or determing what they are.



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

index_pos = 0

for i in d.values():

#Testing and seeing stuff
print("pos:", index_pos)
print(i)
print(len(i))

if len(i) < 2:

del d[???]
#What do I do?

index_pos += 1


I used index_pos because I thought it might be useful but I'm not sure.



I know I can delete an entry from the dictionary using



del d['key']


But how do I avoid using the key and e.g. use the index position instead, or how do I find out what the key is, so I can delete it?



Hopefully I didn't make this too confusing.



Thanks







python dictionary






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 23:14







Mandingo

















asked Nov 24 '18 at 23:11









MandingoMandingo

34229




34229








  • 1





    You could iterate over d.items() so you'll have key-value pairs.

    – Filip Młynarski
    Nov 24 '18 at 23:15














  • 1





    You could iterate over d.items() so you'll have key-value pairs.

    – Filip Młynarski
    Nov 24 '18 at 23:15








1




1





You could iterate over d.items() so you'll have key-value pairs.

– Filip Młynarski
Nov 24 '18 at 23:15





You could iterate over d.items() so you'll have key-value pairs.

– Filip Młynarski
Nov 24 '18 at 23:15












2 Answers
2






active

oldest

votes


















4














Just use a dictionary comprehension:



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}
res = {k: v for k, v in d.items() if len(v) >= 2}


Yes, you are creating a new dictionary, but this in itself is not usually a problem. Any solution will take O(n) time.



You can iterate a copy of your dictionary while modifying your original one. However, you should find the dictionary comprehension more efficient. Don't, under any circumstances, remove or add keys while you iterate your original dictionary.






share|improve this answer
























  • Thanks. Should I remove the old dictionary (as I don't need it) or does it make no difference to anything? Or...?

    – Mandingo
    Nov 24 '18 at 23:17








  • 1





    @Mandingo, It depends what you are looking to do. If you are assigning to the same variable and no longer need the old one, you don't need to do anything further. If you still need access to the original dictionary, just use a new variable name for the filtered one.

    – jpp
    Nov 24 '18 at 23:18













  • Also, why shouldn't I, under any circumstances, remove or add keys whilst I iterate over my original dictionary?

    – Mandingo
    Nov 24 '18 at 23:30






  • 1





    @Mandingo, The docs say: Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. More detail here: Modifying a Python dict while iterating over it.

    – jpp
    Nov 24 '18 at 23:31








  • 1





    Thanks for the help!

    – Mandingo
    Nov 24 '18 at 23:41





















1














If you doesn't want to create new dict here's how you could change your code. Here we iterate over copy of our dict and then delete keys of our original dict if length of its value is less than 2.



d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

for key in d.copy():
if len(d[key]) < 2:
del d[key]

print(d)





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463176%2fremove-items-from-dictionary-if-the-length-of-the-item-is-1-or-less%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    Just use a dictionary comprehension:



    d = {'acd': ['cad'], 'abd': ['bad', 'dab']}
    res = {k: v for k, v in d.items() if len(v) >= 2}


    Yes, you are creating a new dictionary, but this in itself is not usually a problem. Any solution will take O(n) time.



    You can iterate a copy of your dictionary while modifying your original one. However, you should find the dictionary comprehension more efficient. Don't, under any circumstances, remove or add keys while you iterate your original dictionary.






    share|improve this answer
























    • Thanks. Should I remove the old dictionary (as I don't need it) or does it make no difference to anything? Or...?

      – Mandingo
      Nov 24 '18 at 23:17








    • 1





      @Mandingo, It depends what you are looking to do. If you are assigning to the same variable and no longer need the old one, you don't need to do anything further. If you still need access to the original dictionary, just use a new variable name for the filtered one.

      – jpp
      Nov 24 '18 at 23:18













    • Also, why shouldn't I, under any circumstances, remove or add keys whilst I iterate over my original dictionary?

      – Mandingo
      Nov 24 '18 at 23:30






    • 1





      @Mandingo, The docs say: Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. More detail here: Modifying a Python dict while iterating over it.

      – jpp
      Nov 24 '18 at 23:31








    • 1





      Thanks for the help!

      – Mandingo
      Nov 24 '18 at 23:41


















    4














    Just use a dictionary comprehension:



    d = {'acd': ['cad'], 'abd': ['bad', 'dab']}
    res = {k: v for k, v in d.items() if len(v) >= 2}


    Yes, you are creating a new dictionary, but this in itself is not usually a problem. Any solution will take O(n) time.



    You can iterate a copy of your dictionary while modifying your original one. However, you should find the dictionary comprehension more efficient. Don't, under any circumstances, remove or add keys while you iterate your original dictionary.






    share|improve this answer
























    • Thanks. Should I remove the old dictionary (as I don't need it) or does it make no difference to anything? Or...?

      – Mandingo
      Nov 24 '18 at 23:17








    • 1





      @Mandingo, It depends what you are looking to do. If you are assigning to the same variable and no longer need the old one, you don't need to do anything further. If you still need access to the original dictionary, just use a new variable name for the filtered one.

      – jpp
      Nov 24 '18 at 23:18













    • Also, why shouldn't I, under any circumstances, remove or add keys whilst I iterate over my original dictionary?

      – Mandingo
      Nov 24 '18 at 23:30






    • 1





      @Mandingo, The docs say: Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. More detail here: Modifying a Python dict while iterating over it.

      – jpp
      Nov 24 '18 at 23:31








    • 1





      Thanks for the help!

      – Mandingo
      Nov 24 '18 at 23:41
















    4












    4








    4







    Just use a dictionary comprehension:



    d = {'acd': ['cad'], 'abd': ['bad', 'dab']}
    res = {k: v for k, v in d.items() if len(v) >= 2}


    Yes, you are creating a new dictionary, but this in itself is not usually a problem. Any solution will take O(n) time.



    You can iterate a copy of your dictionary while modifying your original one. However, you should find the dictionary comprehension more efficient. Don't, under any circumstances, remove or add keys while you iterate your original dictionary.






    share|improve this answer













    Just use a dictionary comprehension:



    d = {'acd': ['cad'], 'abd': ['bad', 'dab']}
    res = {k: v for k, v in d.items() if len(v) >= 2}


    Yes, you are creating a new dictionary, but this in itself is not usually a problem. Any solution will take O(n) time.



    You can iterate a copy of your dictionary while modifying your original one. However, you should find the dictionary comprehension more efficient. Don't, under any circumstances, remove or add keys while you iterate your original dictionary.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 24 '18 at 23:13









    jppjpp

    101k2164114




    101k2164114













    • Thanks. Should I remove the old dictionary (as I don't need it) or does it make no difference to anything? Or...?

      – Mandingo
      Nov 24 '18 at 23:17








    • 1





      @Mandingo, It depends what you are looking to do. If you are assigning to the same variable and no longer need the old one, you don't need to do anything further. If you still need access to the original dictionary, just use a new variable name for the filtered one.

      – jpp
      Nov 24 '18 at 23:18













    • Also, why shouldn't I, under any circumstances, remove or add keys whilst I iterate over my original dictionary?

      – Mandingo
      Nov 24 '18 at 23:30






    • 1





      @Mandingo, The docs say: Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. More detail here: Modifying a Python dict while iterating over it.

      – jpp
      Nov 24 '18 at 23:31








    • 1





      Thanks for the help!

      – Mandingo
      Nov 24 '18 at 23:41





















    • Thanks. Should I remove the old dictionary (as I don't need it) or does it make no difference to anything? Or...?

      – Mandingo
      Nov 24 '18 at 23:17








    • 1





      @Mandingo, It depends what you are looking to do. If you are assigning to the same variable and no longer need the old one, you don't need to do anything further. If you still need access to the original dictionary, just use a new variable name for the filtered one.

      – jpp
      Nov 24 '18 at 23:18













    • Also, why shouldn't I, under any circumstances, remove or add keys whilst I iterate over my original dictionary?

      – Mandingo
      Nov 24 '18 at 23:30






    • 1





      @Mandingo, The docs say: Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. More detail here: Modifying a Python dict while iterating over it.

      – jpp
      Nov 24 '18 at 23:31








    • 1





      Thanks for the help!

      – Mandingo
      Nov 24 '18 at 23:41



















    Thanks. Should I remove the old dictionary (as I don't need it) or does it make no difference to anything? Or...?

    – Mandingo
    Nov 24 '18 at 23:17







    Thanks. Should I remove the old dictionary (as I don't need it) or does it make no difference to anything? Or...?

    – Mandingo
    Nov 24 '18 at 23:17






    1




    1





    @Mandingo, It depends what you are looking to do. If you are assigning to the same variable and no longer need the old one, you don't need to do anything further. If you still need access to the original dictionary, just use a new variable name for the filtered one.

    – jpp
    Nov 24 '18 at 23:18







    @Mandingo, It depends what you are looking to do. If you are assigning to the same variable and no longer need the old one, you don't need to do anything further. If you still need access to the original dictionary, just use a new variable name for the filtered one.

    – jpp
    Nov 24 '18 at 23:18















    Also, why shouldn't I, under any circumstances, remove or add keys whilst I iterate over my original dictionary?

    – Mandingo
    Nov 24 '18 at 23:30





    Also, why shouldn't I, under any circumstances, remove or add keys whilst I iterate over my original dictionary?

    – Mandingo
    Nov 24 '18 at 23:30




    1




    1





    @Mandingo, The docs say: Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. More detail here: Modifying a Python dict while iterating over it.

    – jpp
    Nov 24 '18 at 23:31







    @Mandingo, The docs say: Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. More detail here: Modifying a Python dict while iterating over it.

    – jpp
    Nov 24 '18 at 23:31






    1




    1





    Thanks for the help!

    – Mandingo
    Nov 24 '18 at 23:41







    Thanks for the help!

    – Mandingo
    Nov 24 '18 at 23:41















    1














    If you doesn't want to create new dict here's how you could change your code. Here we iterate over copy of our dict and then delete keys of our original dict if length of its value is less than 2.



    d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

    for key in d.copy():
    if len(d[key]) < 2:
    del d[key]

    print(d)





    share|improve this answer




























      1














      If you doesn't want to create new dict here's how you could change your code. Here we iterate over copy of our dict and then delete keys of our original dict if length of its value is less than 2.



      d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

      for key in d.copy():
      if len(d[key]) < 2:
      del d[key]

      print(d)





      share|improve this answer


























        1












        1








        1







        If you doesn't want to create new dict here's how you could change your code. Here we iterate over copy of our dict and then delete keys of our original dict if length of its value is less than 2.



        d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

        for key in d.copy():
        if len(d[key]) < 2:
        del d[key]

        print(d)





        share|improve this answer













        If you doesn't want to create new dict here's how you could change your code. Here we iterate over copy of our dict and then delete keys of our original dict if length of its value is less than 2.



        d = {'acd': ['cad'], 'abd': ['bad', 'dab']}

        for key in d.copy():
        if len(d[key]) < 2:
        del d[key]

        print(d)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 23:20









        Filip MłynarskiFilip Młynarski

        1,7961413




        1,7961413






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463176%2fremove-items-from-dictionary-if-the-length-of-the-item-is-1-or-less%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin